Robert J. Robert J. - 1 year ago 151
ASP.NET (C#) Question

Create dynamic links in the navigation panel

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; }

in my controller:

public IActionResult Index()
//This way I dynamically pass data to my View
ViewBag.Categories = _repository.ReturnCategories();
return View();

in my

//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;

Then later in the _Layout where I take care of the navigation:

<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>

The problem occurs with
which does not generate appropriate href in my actual page.

So the question is what am I doing wrong? How can I pass
to my
tag so the links work correctly?

Edit 1 - Adding more code:

Here is what was generated (note the missing href tag)

<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>

Answer Source

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" 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download