自定义HtmlHelper(ActionLink内的图像)

时间:2012-04-09 23:36:27

标签: c# html css asp.net-mvc-3

我已经看到这样做了几种不同的方式,但不是具体的我想要的。我目前有一个自定义的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());
        }

有什么想法吗?

1 个答案:

答案 0 :(得分: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);