I am trying to dynamically create my top navigation panel in ASP.NET Core MVC 6.
I know it's simple but I cannot figure out how to make it work. Here is what I do (simplified):
My Model:
public class IP_Category
{
public int id { get; set; }
public string DisplayName { get; set; }
}
public IActionResult Index()
{
//This way I dynamically pass data to my View
ViewBag.Categories = _repository.ReturnCategories();
return View();
}
cshtml
@{
//this info is in the top of the page, here I retrieve data passed from
//controller and save it as a local variable
var categories = (List<IP_Category>)ViewBag.Categories;
}
<ul class="nav navbar-nav">
<li><a asp-controller="Home" asp-action="Index">Home</a></li>
<li><a asp-controller="Home" asp-action="About">About</a></li>
<li><a asp-controller="Home" asp-action="Contact">Contact</a></li>
@foreach (var category in categories)
{
<li><a asp-controller="Home" asp-action="@category.DisplayName">@category.DisplayName</a></li>
}
</ul>
asp-action="@category.DisplayName"
category.DisplayName
asp-action
<ul class="nav navbar-nav">
<li><a href="/">Home</a></li>
<li><a href="/Home/About">About</a></li>
<li><a href="/Home/Contact">Contact</a></li>
<li><a href="">Item1</a></li>
<li><a href="">Item2</a></li>
</ul>
if the controller and action don't match an existing controller and action then no href will be rendered. I suspect that @category.DisplayName does not match any actual action name on your home controller. Seems more likely that you have an action named Category that expects a parameter corresponding to the @category.DisplayName so it should be passed as a route parameter not as the action name
@foreach (var category in categories)
{
<li><a asp-controller="Home"
asp-action="Category"
asp-route-category="@category.DisplayName">@category.DisplayName</a></li>
}