开发者

Catch method name of controller

开发者 https://www.devze.com 2022-12-21 12:27 出处:网络
I have master page, in the bottom of which I have such menu: <div class=\"footMenu\"> <ul> <li class=\"active\"><a href=\"\">test1</a> </li>

I have master page, in the bottom of which I have such menu:

<div class="footMenu">
    <ul>
        <li class="active"><a href="">test1</a> </li>
        <li><a href="">test2</a></li>
        <li><a href="">test3</a></li>               
    </ul&开发者_如何学编程gt;
</div>

Depending on the loaded view I need to put class="active" in front of the current li item.

How can this be done?


In a asp.net mvc application I usually solve this by setting a id of the body tag that contains both the name of the controller and the name of the action. Then I use css to style links differently depending on the id of the body tag.

I usually do this by creating a html helper extension that gets the id string for the body tag. That can look something like this:

public static string BodyId(this HtmlHelper helper) {
    var controllerName = helper.ViewContext.RouteData.GetRequiredString("controller").ToLower();
    var actionName = helper.ViewContext.RouteData.GetRequiredString("action").ToLower();

    return string.Format("{0}-{1}", controllerName, actionName);
}

Then use it like this:

<body id="<%=Html.BodyId()%>">

Then you can put ids of all your links as well. To make it clearer they can also contain the name of the controller and the name of the action that they should link to. Something like this:

<ul>
    <li><a href="" id="home-index-link">test1</a></li>
    <li><a href="" id="account-login-link">test2</a></li>       
</ul>

Then I use css to style them differently depending on if they are selected or not. Something like this:

#home-index #home-index-link, #account-login #account-login-link {
    /* Styles for selected links */
}

It will, of course, work if you do the same for the <li /> tag instead of the <a /> tag.

If you don't want to do it like that you can of course just use the routedata (as I do in my html helper here). The value with the key "action" will contain the name of the action and the value with the key "controller" will contain the name of the controller.

0

精彩评论

暂无评论...
验证码 换一张
取 消