How could i change layout page from viewpage in mv

2019-09-20 16:47发布

I am working on asp.net mvc 3 with razor. I have a layout(master) page in my project. It contains a side panel with 4 links and place for viewpage(@RenderBody). when user clicks on link1 it redirects to viewpage1 and link1 should be selected, and when he clicks link2 it redirects to viewpage2 and link2 should be selected so on. It redirecting very well to required pages but it always selects the link1 only though i clicked link2,link3,link4. How could i select the appropriate link in layout page from the individual viewpage. guide me.

1条回答
再贱就再见
2楼-- · 2019-09-20 17:27

By selected I guess you mean highlight using CSS, don't you? If this is the case I would propose you to write a custom HTML helper to generate those links:

public static IHtmlString MenuItem(
    this HtmlHelper htmlHelper, 
    string text,
    string action, 
    string controller
)
{
    var li = new TagBuilder("li");
    var routeData = htmlHelper.ViewContext.RouteData;
    var currentAction = routeData.GetRequiredString("action");
    var currentController = routeData.GetRequiredString("controller");
    if (string.Equals(currentAction, action, StringComparison.OrdinalIgnoreCase) &&
        string.Equals(currentController, controller, StringComparison.OrdinalIgnoreCase))
    {
        li.AddCssClass("active");
    }
    li.InnerHtml = htmlHelper.ActionLink(text, action, controller).ToHtmlString();
    return new HtmlString(li.ToString());
}

and then inside your layout use the helper:

<ul>
    @Html.MenuItem("link 1", "Action1", "Controller1")
    @Html.MenuItem("link 2", "Action2", "Controller2")
    ...
</ul>

and now all that's left is to define the .active rule in your CSS class:

.active {
    ... something fancy to pop the currently selected link from the others
}
查看更多
登录 后发表回答