2

我已经看到这有几种不同的方式,但不是我正在寻找的具体方式。我目前有一个自定义 HtmlHelper,它将“class='currentPage'”添加到 ActionLink 以突出显示导航系统中的当前页面。

public static MvcHtmlString MenuItem(
            this HtmlHelper htmlHelper,
            string text,
            string action,
            string controller
        )
        {
            string value;
            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))
            {
                value = htmlHelper.ActionLink(text, action, new { controller = controller }, new { @class = "currentPage" }).ToHtmlString();
                return MvcHtmlString.Create(value.ToString());
            }

            value = htmlHelper.ActionLink(text, action, controller).ToHtmlString();
            return MvcHtmlString.Create(value.ToString());
        }

这很好用,但我有一个管理区域,其中还有一个与每个菜单项关联的图像。该图像位于链接中,如下所示:

<li><a href="/Admin/Blog"><img src="/Content/images/icons/page_edit.png" alt="" /> Blog</a></li>

我想为“MenuItem”创建一个覆盖方法,在 ActionLink 中添加图像,但我有点难过。目前我有以下内容,将 img 标签放在外面......

public static MvcHtmlString MenuItem(
            this HtmlHelper htmlHelper,
            bool isAdmin,
            string text,
            string action,
            string controller
        )
        {
            string value;
            var routeData = htmlHelper.ViewContext.RouteData;
            var currentAction = routeData.GetRequiredString("action");
            var currentController = routeData.GetRequiredString("controller");

            value = "<img src='/Content/images/admin_icons/" + text + ".png' alt='' /> ";

            if (string.Equals(currentAction, action, StringComparison.OrdinalIgnoreCase) &&
                string.Equals(currentController, controller, StringComparison.OrdinalIgnoreCase))
            {
                value += htmlHelper.ActionLink(text, action, new { controller = controller }, new { @class = "currentPage" }).ToHtmlString();

            }
            else
            {
                value += htmlHelper.ActionLink(text, action, controller).ToHtmlString();
            }

            return MvcHtmlString.Create(value.ToString());
        }

有任何想法吗?

4

1 回答 1

0

我会使用 UrlHelper 生成 URL,然后格式化字符串。我的示例不涉及添加条件类,但这应该很容易包含。

        var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
        var url = urlHelper.Action(action, controller);
        var imgUrl = urlHelper.Content("~/Content/images/icons/page_edit.png");
        var html = string.Format("<li><a href=\"{0}\"><img src=\"{2}\" alt=\"\" />{1}</a></li>", url, text, imgUrl);
        return new MvcHtmlString(html);
于 2012-04-10T00:19:51.683 回答