如何使用ActionLikns在MVC4 Razor View中创建菜单?
我是MVC的初学者所以请举个例子吗?
先谢谢
Ankur Tripathi
答案 0 :(得分:5)
以下是一个非常基本菜单的示例:
<ul>
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About us", "About", "Company")</li>
...
</ul>
然后,您可能希望将一些不同的CSS类应用于活动菜单链接。您可以编写自定义HTML帮助程序:
public static class MenuExtensions
{
public static MvcHtmlString 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 MvcHtmlString.Create(li.ToString());
}
}
可以像这样使用:
<ul>
@Html.MenuItem("Home", "Index", "Home")
@Html.MenuItem("About us", "About", "Company")
...
</ul>