如何从自定义帮助程序中使用ASP.NET MVC Html Helpers?

stp*_*tpe 12 asp.net-mvc

我有几个列出搜索结果的页面,对于我想要显示的每个结果,我想创建一个自定义的View Helper,以避免重复显示代码.

如何从自定义视图助手中访问方便的现有视图助手?即在我的自定义视图帮助器中,我想使用Url.Action(),Html.ActionLink等.如何从我的自定义视图助手访问它们?

using System;
namespace MvcApp.Helpers
{
    public class SearchResultHelper
    {
        public static string Show(Result result)
        {
            string str = "";

            // producing HTML for search result here

            // instead of writing
            str += String.Format("<a href=\"/showresult/{0}\">{1}</a>", result.id, result.title);
            // I would like to use Url.Action, Html.ActionLink, etc. How?

            return str;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

using System.Web.Mvc允许访问HtmlHelpers,但没有像ActionLink这样的方便方法.

Mat*_*caj 9

这个例子可以帮到你.此帮助程序根据用户是否登录来呈现不同的链接文本.它演示了在我的自定义助手中使用ActionLink:

    public static string FooterEditLink(this HtmlHelper helper,
        System.Security.Principal.IIdentity user, string loginText, string logoutText)
    {
        if (user.IsAuthenticated)
            return System.Web.Mvc.Html.LinkExtensions.ActionLink(helper, logoutText, "Logout", "Account",
                new { returnurl = helper.ViewContext.HttpContext.Request.Url.AbsolutePath }, null);
        else
            return System.Web.Mvc.Html.LinkExtensions.ActionLink(helper, loginText, "Login", "Account",
                new { returnurl = helper.ViewContext.HttpContext.Request.Url.AbsolutePath }, null);
    }
Run Code Online (Sandbox Code Playgroud)

编辑:
访问该Url.Action()方法所需要做的就是this HtmlHelper helper用类似的东西替换param this UrlHelper urlHelp,然后调用urlHelp.Action(...

希望这可以帮助.