Dis*_*ile 9 c# navigation asp.net-mvc
创建新的MVC项目时,它会使用以下标记创建Site.master:
<div id="menucontainer">
<ul id="menu">
<li><%: Html.ActionLink("Home", "Index", "Home")%></li>
<li><%: Html.ActionLink("About", "About", "Home")%></li>
</ul>
</div>
Run Code Online (Sandbox Code Playgroud)
我想在这里放置代码,如果我在该页面上,将突出显示当前链接.
如果我添加另一个链接,例如:
<li><%: Html.ActionLink("Products", "Index", "Products")%></li>
Run Code Online (Sandbox Code Playgroud)
如果我在Products控制器中执行任何操作,我希望Products链接处于活动状态(使用类似.active的css类).
如果我在HomeController About操作上,那么About链接应该是活动的.如果我在HomeController的Index操作上,Home链接应该是活动的.
在MVC中执行此操作的最佳方法是什么?
cod*_*ger 23
看看这篇博文
它显示了如何创建您调用的HTML扩展而不是通常Html.ActionLink的扩展名然后附加class="selected"到当前活动的列表项.
然后,您可以在CSS中放置您想要的任何格式/突出显示
编辑
只是添加一些代码而不仅仅是一个链接.
public static class HtmlHelpers
{
public static MvcHtmlString MenuLink(this HtmlHelper htmlHelper,
string linkText,
string actionName,
string controllerName
)
{
string currentAction = htmlHelper.ViewContext.RouteData.GetRequiredString("action");
string currentController = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");
if (actionName == currentAction && controllerName == currentController)
{
return htmlHelper.ActionLink(linkText, actionName, controllerName, null, new { @class = "selected" });
}
return htmlHelper.ActionLink(linkText, actionName, controllerName);
}
}
Run Code Online (Sandbox Code Playgroud)
现在,您需要selected在CSS中定义类,然后在视图using中在顶部添加语句.
@using ProjectNamespace.HtmlHelpers
并使用MenuLink而不是ActionLink
@Html.MenuLink("Your Menu Item", "Action", "Controller")
Men*_*tor 10
您可以通过使用"data-"属性来标识容器然后使用链接的jQuery更改CSS类来执行此操作,如下所示:
<div class="..." data-navigation="true">
<ul class="...">
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
</div>
<script>
$(function () {
$("div[data-navigation='true']").find("li").children("a").each(function () {
if ($(this).attr("href") === window.location.pathname) {
$(this).parent().addClass("active");
}
});
});
</script>
Run Code Online (Sandbox Code Playgroud)
以下是将其作为MVC帮助程序实现的方法:
@helper NavigationLink(string linkText, string actionName, string controllerName)
{
if(ViewContext.RouteData.GetRequiredString("action").Equals(actionName, StringComparison.OrdinalIgnoreCase) &&
ViewContext.RouteData.GetRequiredString("controller").Equals(controllerName, StringComparison.OrdinalIgnoreCase))
{
<span>@linkText</span>
}
else
{
@Html.ActionLink(linkText, actionName, controllerName);
}
}
Run Code Online (Sandbox Code Playgroud)
然后可以使用类似于以下内容:
@NavigationLink("Home", "index", "home")
@NavigationLink("About Us", "about", "home")
Run Code Online (Sandbox Code Playgroud)
关于MVC助手的好文章可以在这里找到:http://weblogs.asp.net/scottgu/archive/2011/05/12/asp-net-mvc-3-and-the-helper-syntax-within-razor的.aspx
| 归档时间: |
|
| 查看次数: |
31693 次 |
| 最近记录: |