Asp.Net Mvc突出显示当前的页面链接技术?

ber*_*slu 25 asp.net asp.net-mvc

我需要在菜单中突出显示活动链接.顺便说一下,我的菜单在主页面中.我正在寻找实现这个的最佳方法?有任何想法吗?

Dar*_*rov 38

处理此问题的最佳方法是编写HTML帮助程序.您可以使用 RouteData.Values["action"]获取当前正在执行的操作并与菜单名称进行比较,如果它们匹配,则应用将突出显示它的CSS类.

public static MvcHtmlString MenuItem(
    this HtmlHelper htmlHelper, 
    string action, 
    string text
)
{
    var menu = new TagBuilder("div");
    var currentAction = (string)htmlHelper.ViewContext.RouteData.Values["action"];
    if (string.Equals(
            currentAction, 
            action,
            StringComparison.CurrentCultureIgnoreCase)
    )
    {
        menu.AddCssClass("highlight");
    }
    menu.SetInnerText(text);
    return MvcHtmlString.Create(menu.ToString());
}
Run Code Online (Sandbox Code Playgroud)

然后使用此帮助程序呈现菜单项:

<%: Html.MenuItem("about", "About us") %>
<%: Html.MenuItem("contact", "Contact us") %>
...
Run Code Online (Sandbox Code Playgroud)

  • 嗨,达林.一个人把HTML助手放在哪里?一个新的文件夹然后使用"导入"来包含它?我怎么用这个?谢谢. (2认同)
  • 放置自定义HTML帮助程序没有任何约定或特定位置.我个人将扩展方法放在Helpers文件夹中. (2认同)

İbr*_*lük 7

我总是使用这个解决方案Html Part

<ul>
   @Html.ListItemAction("Home Page","Index","Home")
   @Html.ListItemAction("Manage","Index","Home")
</ul>
Run Code Online (Sandbox Code Playgroud)

助手部分

 public static class ActiveLinkHelper
    { 
      public static MvcHtmlString ListItemAction(this HtmlHelper helper, string name, string actionName, string controllerName)
      {
        var currentControllerName = (string)helper.ViewContext.RouteData.Values["controller"];
        var currentActionName = (string)helper.ViewContext.RouteData.Values["action"];
        var sb = new StringBuilder();
        sb.AppendFormat("<li{0}", (currentControllerName.Equals(controllerName, StringComparison.CurrentCultureIgnoreCase) &&
                                            currentActionName.Equals(actionName, StringComparison.CurrentCultureIgnoreCase)
                                                ? " class=\"active\">" : ">"));
        var url = new UrlHelper(HttpContext.Current.Request.RequestContext);
        sb.AppendFormat("<a href=\"{0}\">{1}</a>", url.Action(actionName, controllerName), name);
        sb.Append("</li>");
        return new MvcHtmlString(sb.ToString());
   }
}
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

15234 次

最近记录:

5 年,11 月 前