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