通常,在ASP.NET视图中,可以使用以下函数来获取URL (而不是<a>
):
Url.Action("Action", "Controller");
但是,我找不到如何从自定义HTML帮助器中执行此操作。我有过
public class MyCustomHelper
{
public static string ExtensionMethod(this HtmlHelper helper)
{
}
}
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的实例。肯定有更简单的方法。
发布于 2009-09-18 10:27:58
您可以在html helper扩展方法中像这样创建url helper:
var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
var url = urlHelper.Action("Home", "Index")
发布于 2013-01-24 18:20:47
您还可以使用UrlHelper
公共和静态类获取链接:
UrlHelper.GenerateUrl(null, actionName, controllerName, null, null, null, routeValues, htmlHelper.RouteCollection, htmlHelper.ViewContext.RequestContext, true)
在本例中,您不必创建新的UrlHelper类,这可能会带来一些好处。
发布于 2013-05-29 19:13:32
下面是我的小扩展方法,用于获取HtmlHelper
实例的UrlHelper
:
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');
//...
}
(我张贴这篇文章仅供参考)
https://stackoverflow.com/questions/1443647
复制相似问题