【问题标题】:Generate URL in HTML helper在 HTML 帮助程序中生成 URL
【发布时间】:2010-11-29 10:36:48
【问题描述】:

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

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

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

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

辅助变量具有 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");
    }
}

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

【问题讨论】:

  • 我意识到这是一个简化的示例,但对于显示的示例,我将扩展 UrlHelper 而不是 HtmlHelper。不过,您的真实代码可能两者都需要。
  • 对不起,我应该更清楚:我想在扩展方法中做一些 HTML 渲染,我需要为它生成 URL。

标签: asp.net-mvc url html-helper


【解决方案1】:

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

var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
var url = urlHelper.Action("Home", "Index")

【讨论】:

  • 我认为如果构造函数也初始化RouteCollection new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection)
【解决方案2】:

您还可以使用UrlHelper public 和 static 类获取链接:

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

在此示例中,您不必创建新的 UrlHelper 类,这可能会有一点优势。

【讨论】:

  • 我更喜欢这个答案,因为设置了 RouteCollection。
【解决方案3】:

这是我获取UrlHelperHtmlHelper 实例的微型扩展方法:

  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');
    //...
}

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

【讨论】:

  • 优秀的方法,因为它重用现有对象而不是创建新对象。
  • 我们使用的是 ASP.NET 4.5 并且遇到了重入问题。我们不相信 UrlHelper 可以跨 http 请求重用。请注意。
猜你喜欢
  • 2013-06-10
  • 2014-02-20
  • 1970-01-01
  • 2014-06-04
  • 1970-01-01
  • 2012-02-05
  • 2015-03-16
  • 2015-02-05
  • 2014-12-06
相关资源
最近更新 更多