Adding “active” tag to navigation list in an asp.net mvc master page

后端 未结 15 1867
渐次进展
渐次进展 2020-12-12 13:31

In the default asp.net mvc project, in the Site.Master file, there is a menu navigation list:

15条回答
  •  粉色の甜心
    2020-12-12 14:07

    The fact that your View has to know about your controller's actions is breaking with the MVC pattern. Perhaps your controller could pass some "control" information to the view to ultimately allow it to accomplish the same thing, the only difference is who is in charge.

    Like in your controller's action you could:

    public ActionResult Index(){
         ViewData["currentAction"] = "Index";
         //... other code
        return View();
    }
    

    Then over in your view you could:

    <% if( ((string)ViewData["currentAction"]) == "Index" {%> <% } %>
    <% if( ((string)ViewData["currentAction"]) == "SomethingElse" {%> <% } %>
    

    However, the more I think about it the more I question why you are using the same View for multiple actions. Is the view that similar?

    If the use case justifies it then go with my above suggestion. But otherwise perhaps you could break things out into multiple views (one for each controller action) and the problem solves itself.

提交回复
热议问题