169

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

Url.Action("Action", "Controller");

但是,我无法从自定义 HTML 帮助程序中找到如何做到这一点。我有

public class MyCustomHelper
{
   public static string ExtensionMethod(this HtmlHelper helper)
   {
   }
}

辅助变量具有 Action 和 GenerateLink 方法,但它们生成<a>'s. 我在 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");
    }
}

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

4

3 回答 3

220

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

var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
var url = urlHelper.Action("Home", "Index")
于 2009-09-18T10:27:57.850 回答
22

You can also get links using UrlHelper public and static class:

UrlHelper.GenerateUrl(null, actionName, controllerName, null, null, null, routeValues, htmlHelper.RouteCollection, htmlHelper.ViewContext.RequestContext, true)

In this example you don't have to create new UrlHelper class what could be a little advantage.

于 2013-01-24T10:20:47.063 回答
10

这是我获取实例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];
        }
    }

将其用作:

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

(我发布这个答案仅供参考)

于 2013-05-29T11:13:32.253 回答