Url.Action within #helper does not raise event - asp.net-mvc

I am having issues with an Action link within the #helper.
See below this line
<a href="#Url.Action("Index","Category", new { id = item.Id })">
It simply does not raise event. What am i doing wrong here?
#helper ShowTree(IEnumerable<FrontEnd.Controllers.SharedController.Category> categories)
{
<ul id="#(Added == false ? "categories" : "")" class="parent-1">
#foreach (FrontEnd.Controllers.SharedController.Category item in categories)
{
Added = true;
<li class="child-1 has-sublist">
<a href="#Url.Action("Index","Category", new { id = item.Id })">
#item.CategoryName
#if (item.Children.Count > 0)
{ <span>
[#item.Children.Count]
</span>
}
</a>
#if (item.Children.Any())
{
#ShowTree(item.Children)
}
</li>
}
</ul>
}

Have you tried something like the following??
#Html.ActionLink(item.CategoryName, "Index", "Listing", new { id = item.Id }, null, null)
https://msdn.microsoft.com/en-us/library/dd460522(v=vs.118).aspx

Ok. Just found the cure.
Javascript was blocking the request to the controller..
$('#categories > li a').click(function(e){
if($(this).parent().hasClass('has-sublist')) {
e.preventDefault();
}....
.................

Related

KnockoutJS with MVC Partialview

I am having problems persisting data from KO observableArray in a MVC Partialview...
I have a side navigation menu where one of the nodes is dynamically built using KOjs 'foreach', and this navigation menu should persist across the site. The menu is rendered ok on the first View page but when I navigate on other page (clicking on menu option or any way) the dynamic node is empty, although the observableArrays were fetched and loaded with the correct data.
It seems like the navigaition menu (which is a partial view) is not refreshing/reloading to render the menu nodes/options again.
Any help si much appreciated. TIA!
self.reports = ko.observableArray([]);
self.reportCategories = ko.observableArray([]);
self.getReports = function () {
App.Server.get("/.../reports/")
.then(function (vm) {
self.reports(vm.reports);
self.reportCategories(vm.categories);
});
};
self.init = function () {
self.getReports();
};
self.init();
<li>
<a class="level1" data-toggle="collapse" href="#report-submenu" aria-expanded="false" aria-controls="collapseExample">Reports</a>
<ul class="level1 collapse" id="report-submenu" data-bind="foreach: reportCategories">
<li>
<a class="level2 collapse" data-toggle="collapse" data-bind="text: label, attr: { href: '#' + value }"
aria-expanded="false" aria-controls="collapseExample"></a>
<ul class="level2 collapse" data-bind="foreach: reports, attr: { id: value }">
<li data-bind="if: category == $parent.categoryId">
<a class="level3" data-bind="text: menuName, attr: { href: reportName }"></a>
</li>
</ul>
</li>
Here's the other part of the code (a Nancy GET method):
Get["/"] = _ =>
{
var reportModel = new ReportModel();
var reports = reportService.GetList();
if (reports != null)
{
// Categories
reportModel.Categories = reports.Select(s => s.Category).Distinct().Select(c => new ReportCategoryModel()
{
CategoryId = c,
Label = c.TrimStart("Reports/".ToCharArray()),
Value = c.ToLower().Replace('/', '-')
}).ToList();
// Reports
reportModel.Reports = reports.Select(r => new ReportRecord()
{
MenuName = r.MenuName,
ReportName = r.ReportName,
Category = r.Category,
}).ToList();
}
return Response.AsJson(reportModel);
};

Problems with partialview data

I have a problem with a partial view. The first time when it is rendered everything is ok, but after that some data is loosed.
This is how my page should look: this is when the partial view is rendered the first time
but when I'm clicking on a category to check his subcategories, the image is null, it is not visible anymore. (only the name is visible)
This is my partial view:
#model IEnumerable<OnlineCarStore.Models.CategoriesVM>
<div class="container">
<div class="row">
#using (Html.BeginForm("SubCategories", "Product"))
{
<div class="list-group col-sm-3" style="width:280px;">
#{var selected = string.Empty;
if (#HttpContext.Current.Session["selectedCar"] == null)
{
selected = string.Empty;
}
else
{
selected = #HttpContext.Current.Session["selectedCar"].ToString();
}
foreach (var c in Model)
{
<a href="#Url.Action("SubCategories", "Product", new { selected = #selected, id = #c.ID, category = #c.CategoryName })" class="list-group-item">
<span> #c.CategoryName</span>
</a>
}
}
</div>
<div class="col-sm-9">
#foreach (var c in Model)
{
<div class="card-group" style="width:200px; display: inline-block">
<div class="card card">
<a href="#Url.Action("SubCategories", "Product", new { selected = #HttpContext.Current.Session["selectedCar"].ToString(), id = #c.ID, category = #c.CategoryName })" id="linkOnImg" class="card-group">
<img class="card-img-top center-block" src="#string.Format("../content/images/categories/{0}.jpg", #c.AtpID)" alt=#c.CategoryName style="padding-top: 5px">
<div class="card-text text-center">
<p class="category-card-title ">
<span class="text-muted">#c.CategoryName</span>
</p>
</div>
</a>
</div>
</div>
}
</div>
}
</div>
and this is the Subcategoris view, where the partial view is rendered second time:
<div class="container">
<div class="row">
#Html.Partial("/Views/Home/CategorieTypes.cshtml");
Here is the Product controller Subcategories method:
public ActionResult SubCategories(string selected, int id, string category)
{
List<CategoriesVM> listOfCategories = new List<CategoriesVM>();
var list = db.Categories.ToList();
var root = list.GenerateTree(c => c.ID, c => c.ParentId).ToList();
TreeItem<Categories> found = null;
var test = new TreeItem<Categories>();
foreach (var rootNode in root)
{
found = TreeGenerator.Find(rootNode, (n) => n.Item.ID == id);
if (found != default(TreeItem<Categories>))
{
test = found;
break;
}
}
foreach (var item in found.Children.ToList())
{
CategoriesVM categoryv = new CategoriesVM();
categoryv.ID = item.Item.ID;
categoryv.AtpID = item.Item.AtpID;
categoryv.Childrens = item.Children.ToList();
categoryv.CategoryName = item.Item.AtpName;//.Name;
listOfCategories.Add(categoryv);
}
SiteMaps.Current.CurrentNode.Title = selected + " " + category;
var tests = found.Children.ToList();
if (found.Children.ToList().Count == 0 )
{
return View("Index");
}
else
{
return View("SubCategories", listOfCategories);
}
}
I've checked in developer tool if the source for the image is correct, and although it is correct, the image is not showed:
Can you please help me in this problem? What I do wrong? Why the images don't appear after the first render of the partial view? Thanks in advance!
The path of the partial view is /Views/Home/CategorieTypes.cshtml and the path of the images is /Content/images/categories. In the partial view you are using ../content/images/categories/ as the path of the images which means that it will search for the path /Views/Content/Images/Categories which is invalid.
Remove the two dots in the src property and add a ~ so it will be like: ~/Content/Images/Categories/{img}.
or
Add one more ../ in order to go one level down to the directory like:
../../Content/Images/Categories/{img}

Best way to write razor (format issue)

Hi I have the following code in razor:
#{
foreach (var item in this.Model)
{
if (item.Items == null)
{
#: <li #{if (item.Active) { <text> class="active" </text> } }>
if (item.SpanClass == null)
{
#: </i><span> #item.Text </span>
}else
{
#: </i><span> #item.Text <span class="#item.SpanClass">#item.SpanValue</span></span>
}
}
#: </li>
}
}
It looks like this:
But I go to:
Then the code format is destroyed:
Any clue?
I would do something like that
#{
foreach (var item in this.Model)
{
var activeClass = item.Active ? "active" : "";
if (item.Items == null)
{
<li class="#activeClass">
#if (item.SpanClass == null)
{
<i class="#item.Icon"></i><span> #item.Text </span>
}
else
{
<i class="#item.Icon"></i><span> #item.Text <span class="#item.SpanClass">#item.SpanValue</span></span>
}
</li>
}
}
}

MVC Menu children

I have an MVC menu that is being populated from the database. I have code for it to reach the 4th menu child. I am wondering if there is a better way to write this code in my cshtml so that it detects menu children automatically and i dont have to hard code the menu to a certain level. Thanks for your help.
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
#foreach (var menuLevel1 in navbarmenu)
{
<li class="dropdown">
<a href="~/CATS/Default.aspx">
#menuLevel1.MenuName<span class="caret"></span>
</a>
#{var navbarsubmenu = myMenu.Where(x => x.ParentID == menuLevel1.MenuID && x.IsDeleted == false && x.IsEnabled == true).ToList().OrderBy(x => x.MenuName);}
#if (navbarsubmenu.IsAny())
{
<ul class="dropdown-menu">
#foreach (var menuLevel2 in navbarsubmenu)
{
<li class="dropdown-submenu">
#if (menuLevel2.MenuLink != null && menuLevel2.MenuLink != "")
{
<a href="#Url.Content(menuLevel2.MenuLink)">
#menuLevel2.MenuName
</a>
}
else
{
<a href="~/CATS/Default.aspx">
#menuLevel2.MenuName
</a>
}
#{var navbarsubmenu2 = myMenu.Where(x => x.ParentID == menuLevel2.MenuID && x.IsDeleted == false && x.IsEnabled == true).ToList().OrderBy(x => x.MenuName);}
#if (navbarsubmenu2.IsAny())
{
<ul class="dropdown-menu">
#foreach (var menuLevel3 in navbarsubmenu2)
{
<li class="dropdown-submenu">
#if (menuLevel3.MenuLink != null && menuLevel3.MenuLink != "")
{
<a href="#Url.Content(menuLevel3.MenuLink)">
#menuLevel3.MenuName
</a>
}
else
{
<a href="~/CATS/Default.aspx">
#menuLevel3.MenuName
</a>
}
#{var navbarsubmenu3 = myMenu.Where(x => x.ParentID == menuLevel3.MenuID && x.IsDeleted == false && x.IsEnabled == true).ToList().OrderBy(x => x.MenuName);}
#if (navbarsubmenu3.IsAny())
{
<ul class="dropdown-menu">
#foreach (var menuLevel4 in navbarsubmenu3)
{
<li class="dropdown-submenu">
#if (menuLevel4.MenuLink != null && menuLevel4.MenuLink != "")
{
<a href="#Url.Content(menuLevel4.MenuLink)">
#menuLevel4.MenuName
</a>
}
else
{
<a href="~/CATS/Default.aspx">
#menuLevel4.MenuName
</a>
}
</li>
}
</ul>
}
</li>
}
</ul>
}
</li>
}
</ul>
}
</li>
}
</ul>
Recursive Method as recommended by StephenMuecke
public static class MenuChildExtensions
{
public static MvcHtmlString MenuChild(this HtmlHelper helper, Menu menu)
{
return MvcHtmlString.Create(MenuChildren(menu));
}
private static string MenuChildren(Menu menu)
{
StringBuilder html = new StringBuilder();
TagBuilder div = new TagBuilder("div");
div.InnerHtml = menu.Name;
html.Append(div.ToString());
if (menu.MenuItems != null)
{
foreach (Menu menuchildMenu in menu.MenuItems)
{
html.Append(MenuChildren(menuchildMenu));
}
}
TagBuilder item = new TagBuilder("li");
item.InnerHtml = html.ToString();
TagBuilder container = new TagBuilder("ul");
container.InnerHtml = item.ToString();
return container.ToString();
}
}
}

Checkbox in ListView with Jquery mobile

I am starting to learn HTML5 and CSS (with Jquery Mobile), and because I do not have much background in this area, I am stuck at something very easy.
I want to put a checkbox in a listview (at each li).
How can I do it in order to look like that :
http://a4.mzstatic.com/us/r1000/095/Purple/ff/1d/33/mzl.ecpvufek.320x480-75.jpg
(I mean that the checkbox is at the left of the others text and all).
For the moment, my code is : http://jsfiddle.net/AzN7S/
And as you can see the checkbox is above the text, and even with a div with a float:left in the second li, it doesn't work :(
Can you help me please ?
Thank you very much beforehand for your answer, and sorry for my english ^^
Have a great day.
Olivier.
EDIT :
I finally succeeded in adding a checkbox at the left of the the right part.
I updated my example : http://jsfiddle.net/AzN7S/2/
I do not know if it is the right method, but it works :)
i rethought my old answer and re did the issue especially to fit the mvc 4 framework but the client side is all the same.
so lets start:
if you just want the html you can get it here
this link is to a 3 parts checkbox list, the checkbox, the link to the item and the info popup:
Here is the link to jsfiddle for working listview with checkbox AND icon
iv added at the end some 2 parts listbox and a single part, for any questions let me know.
now for the controller all you need to do is
[Authorize]
public ActionResult Items(string act,
string tab, string search_by, string search, string sort, string sortdir, int? page, int? resultsPerPage,
List<int> selected, int? projectId, string username)
{
if (act == "AddItemsToUser")
{
string response;
if (selected != null)
{
response = "Project Items Added:";
foreach (var item in selected)
{
try
{
if (username != null)
if (UserItemRecordModel.InsertUserItem(username, item, null, null, 0, null, null))
response += item + " - inserted, ";
}
catch (Exception ex)
{
response += item + " - " + ex.Message + ", ";
}
}
response.TrimEnd(' ', ',');
}
else
{
response = "No Items Were Selected!";
}
return Json(response, JsonRequestBehavior.AllowGet);
}
else if (act == "AddItemsToProject")
{
string response;
if (selected != null)
{
response = "Project Items Added:";
foreach (var item in selected)
{
try
{
if (projectId != null)
if (ProjectItemRecordModel.InsertProjectItem(projectId.ToString(), item, null, null, 0, null, null))
response += item + " - inserted, ";
}
catch (Exception ex)
{
response += item + " - " + ex.Message + ", ";
}
}
response.TrimEnd(' ', ',');
}
else
{
response = "No Items Were Selected!";
}
return Json(response, JsonRequestBehavior.AllowGet);
}
else if (act == "RemoveItemsFromUser")
{
string response;
if (selected != null)
{
response = "Project Items Removed:";
foreach (var item in selected)
{
try
{
if (UserItemRecordModel.DeleteUserItem(username, item))
response += item + " - deleted, ";
}
catch (Exception ex)
{
response += item + " - " + ex.Message + ", ";
}
}
response.TrimEnd(' ', ',');
}
else
{
response = "No Items Were Selected!";
}
return Json(response, JsonRequestBehavior.AllowGet);
}
else if (act == "RemoveItemsFromProject")
{
string response;
if (selected != null)
{
response = "Project Items Removed:";
foreach (var item in selected)
{
if (ProjectItemRecordModel.DeleteProjectItem(projectId.ToString(), item))
response += item + " - deleted, ";
}
response.TrimEnd(' ', ',');
}
else
{
response = "No Items Were Selected!";
}
return Json(response, JsonRequestBehavior.AllowGet);
}
List<ItemRecordModel> items = ItemRecordModel.GetSensors(search_by, search, sort, sortdir);
return View("Items", new AdminRecordsViewModel() { Records = items });
}
this was my old answer:
i solved your problem you need to change some stuff but you can accomplish a searchable listview with checkbox like so:
jsfiddle example:
basic:
basic jsfiddle version
nicer version:
nicer version
jquery mobile listview with checkbox and icon or image
here is a listView of checkBox and a search bar. you should add this js code
$("li").on("tap",function(){
$(this).find('label').click();
}); in the button somewhere in your page.
the js code crete a click on the check box when the user clicks on the li
<div class="ui-content" data-role="main">
<div data-role="main" class="ui-content">
<h2 class="settings-h2">Select category</h2>
<h5 lass="settings-h2">You will get articles on those subject,you can change your selection at any time.</h5>
<form class="ui-filterable">
<input id="myFilter-settings" data-type="search">
</form>
<ul data-role="listview" id="ScheduleList-settings" data-filter="true" data-input="#myFilter-settings" data-inset="true" class="ui-listview ui-listview-inset ui-corner-all ui-shadow">
<li data-icon="false">
<form>
<fieldset class="myhover" data-role="controlgroup" data-iconpos="right" >
<input type="checkbox" name="checkbox-h-6a" id="checkbox-Sports" >
<label for="checkbox-Sports">Sports</label>
</fieldset>
</form>
</li>
<li data-icon="false" >
<form>
<fieldset data-role="controlgroup" data-iconpos="right" >
<input type="checkbox" name="checkbox-h-6a" id="ccheckbox-Food" >
<label for="ccheckbox-Food">Food</label>
</fieldset>
</form>
</li>
<li data-icon="false" >
<form>
<fieldset data-role="controlgroup" data-iconpos="right" >
<input type="checkbox" name="checkbox-h-6a" id="checkbox-Politics" >
<label for="checkbox-Politics">Politics </label>
</fieldset>
</form>
</li>
<li data-icon="false" >
<form>
<fieldset data-role="controlgroup" data-iconpos="right" >
<input type="checkbox" name="checkbox-h-6a" id="checkbox-Fashion" >
<label for="checkbox-Fashion">Fashion</label>
</fieldset>
</form>
</li>
</ul>
</div>
</div>

Resources