我猜这个 MenuItem 是您编写的或从某人那里获取的扩展方法,我也猜他们正在包装一个 ActionLink 方法,如:
public static string MenuItem(this HtmlHelper helper, string linkText, string actionName, string controllerName)
{
string currentControllerName = (string)helper.ViewContext.RouteData.Values["controller"];
string currentActionName = (string)helper.ViewContext.RouteData.Values["action"];
// Add selected class
if (currentControllerName.Equals(controllerName, StringComparison.CurrentCultureIgnoreCase) && currentActionName.Equals(actionName, StringComparison.CurrentCultureIgnoreCase))
return string.Concat("<li class=\"selected\">", helper.ActionLink(linkText, actionName, controllerName), "</li>");
// Add link
return string.Concat("<li>", helper.ActionLink(linkText, actionName, controllerName), "</li>");
}
如果是这种情况,只需将 css 类作为参数,并使用接收 html 属性的 ActionLink,如下所示:
public static string MenuItem(this HtmlHelper helper, string linkText, string actionName, string controllerName, string cssClass = "menu-item")
{
string currentControllerName = (string)helper.ViewContext.RouteData.Values["controller"];
string currentActionName = (string)helper.ViewContext.RouteData.Values["action"];
// Add selected class
if (currentControllerName.Equals(controllerName, StringComparison.CurrentCultureIgnoreCase) && currentActionName.Equals(actionName, StringComparison.CurrentCultureIgnoreCase))
return string.Concat("<li class=\"selected\">", helper.ActionLink(linkText, actionName, controllerName), "</li>");
// Add link
return string.Concat("<li>", helper.ActionLink(linkText, actionName, controllerName, new {@class = cssClass} ), "</li>");
}
那么你就这样称呼他们:
<%= Html.MenuItem("Home", "Home", "Index", "index-tem")%>