How to create a reusable navigation menu in ASP MVC3?

I have the following navigation html / code, which is now duplicated across multiple views:

<ul class="topNav"> <li class="selected">@Html.ActionLink("Dashboard", "Dashboard", new { id = ViewContext.RouteData.GetRequiredString("id") })</li> <li>@Html.ActionLink("Stats", "Stats", new { id = ViewContext.RouteData.GetRequiredString("id") })</li> <li>@Html.ActionLink("Questions", "Questions", new { id = ViewContext.RouteData.GetRequiredString("id") })</li> <li>@Html.ActionLink("Answers", "Answers", new { id = ViewContext.RouteData.GetRequiredString("id") })</li> <li>@Html.ActionLink("Contacts", "Contacts", new { id = ViewContext.RouteData.GetRequiredString("id") })</li> </ul> 

Of course, in each view, class="selected" li changes. Is there an easy way to place this block of code in a partial or layout view?

Also, should I use ViewContext.RouteData.GetRequiredString("id") to go to the id parameter of the controller or is there an easier way?

+4
source share
2 answers

Here are two ways to handle this.

  • If you want to really reuse (application-independent solution), you must create the HtmlHelper method Create custom HTML helpers

  • If you need it only in your application, think about it.

     public static class ControllerHelper { /// <summary> /// Checks the current action via RouteData /// </summary> /// <param name="helper">The HtmlHelper object to extend</param> /// <param name="actionName">The Action</param> /// <param name="controllerName">The Controller</param> /// <returns>Boolean</returns> public static bool IsCurrentAction(this HtmlHelper helper, string actionName, string controllerName) { string currentControllerName = (string)helper.ViewContext.RouteData.Values["controller"]; string currentActionName = (string)helper.ViewContext.RouteData.Values["action"]; if (currentControllerName.Equals(controllerName, StringComparison.CurrentCultureIgnoreCase) && currentActionName.Equals(actionName, StringComparison.CurrentCultureIgnoreCase)) return true; return false; } } <ul class="topNav"> <li @if(Html.IsCurrentAction("DashBoard", "DashBoard")) { <text>class="selected"</text> }>@Html.ActionLink("Dashboard", "Dashboard", new { id = ViewContext.RouteData.GetRequiredString("id") })</li> <li>@if(Html.IsCurrentAction("Stats", "Stats")) { <text>class="selected"</text> }>@Html.ActionLink("Stats", "Stats", new { id = ViewContext.RouteData.GetRequiredString("id") })</li> // .... </ul> 

Please tell me, if you want to implement the first approach, I provided additional help

hope this helps

+1
source

You can create a static helper method in the App_code folder. See Reusing @helpers for Multiple Views

And you can take a parameter to determine which LI the selected class should have.

0
source

Source: https://habr.com/ru/post/1383687/


All Articles