在HTML帮助器中生成URL

Jan*_*ich 167 url asp.net-mvc html-helper

通常在ASP.NET视图中,可以使用以下函数来获取URL(而不是a <a>):

Url.Action("Action", "Controller");
Run Code Online (Sandbox Code Playgroud)

但是,我无法从自定义HTML帮助程序中找到如何执行此操作.我有

public class MyCustomHelper
{
   public static string ExtensionMethod(this HtmlHelper helper)
   {
   }
}
Run Code Online (Sandbox Code Playgroud)

辅助变量具有Action和GenerateLink方法,但它们生成了<a>.我在ASP.NET MVC源代码中做了一些挖掘,但我找不到一种简单的方法.

问题是上面的Url是视图类的成员,并且对于它的实例化,它需要一些上下文和路由映射(我不想处理它,我不应该这样做).或者,HtmlHelper类的实例也有一些上下文,我假设它是Url实例的上下文信息子集的晚餐(但我不想再处理它).

总而言之,我认为这是可能的,但是由于我可以看到的所有方式,涉及一些或多或少的内部ASP.NET内容的操作,我想知道是否有更好的方法.

编辑:例如,我看到的一种可能性是:

public class MyCustomHelper
{
    public static string ExtensionMethod(this HtmlHelper helper)
    {
        UrlHelper urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
        urlHelper.Action("Action", "Controller");
    }
}
Run Code Online (Sandbox Code Playgroud)

但这似乎不对.我不想自己处理UrlHelper的实例.必须有一个更简单的方法.

Dar*_*rov 216

你可以在html helper扩展方法中创建这样的url helper:

var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
var url = urlHelper.Action("Home", "Index")
Run Code Online (Sandbox Code Playgroud)

  • 我认为如果构造函数也初始化RouteCollection`new UrlHelper(htmlHelper.ViewContext.RequestContext,htmlHelper.RouteCollection)会更好. (2认同)

cry*_*yss 21

您还可以使用UrlHelper公共和静态类获取链接:

UrlHelper.GenerateUrl(null, actionName, controllerName, null, null, null, routeValues, htmlHelper.RouteCollection, htmlHelper.ViewContext.RequestContext, true)
Run Code Online (Sandbox Code Playgroud)

在这个例子中,您不必创建新的UrlHelper类,这可能是一个小优势.


Kib*_*ria 10

这里是让我的小extenstion方法UrlHelper一的HtmlHelper实例:

  public static partial class UrlHelperExtensions
    {
        /// <summary>
        /// Gets UrlHelper for the HtmlHelper.
        /// </summary>
        /// <param name="htmlHelper">The HTML helper.</param>
        /// <returns></returns>
        public static UrlHelper UrlHelper(this HtmlHelper htmlHelper)
        {
            if (htmlHelper.ViewContext.Controller is Controller)
                return ((Controller)htmlHelper.ViewContext.Controller).Url;

            const string itemKey = "HtmlHelper_UrlHelper";

            if (htmlHelper.ViewContext.HttpContext.Items[itemKey] == null)
                htmlHelper.ViewContext.HttpContext.Items[itemKey] = new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection);

            return (UrlHelper)htmlHelper.ViewContext.HttpContext.Items[itemKey];
        }
    }
Run Code Online (Sandbox Code Playgroud)

用它作为:

public static MvcHtmlString RenderManagePrintLink(this HtmlHelper helper, )
{    
    var url = htmlHelper.UrlHelper().RouteUrl('routeName');
    //...
}
Run Code Online (Sandbox Code Playgroud)

(我发布此ans仅供参考)