通常在ASP.NET视图人们可以使用以下函数来获取的URL(不是<a>
):
Url.Action("Action", "Controller");
但是,我无法找到如何从一个自定义的HTML帮助做到这一点。 我有
public class MyCustomHelper
{
public static string ExtensionMethod(this HtmlHelper helper)
{
}
}
助手变量的动作和GenerateLink方法,但它们产生<a>
的。 我的确在ASP.NET MVC源代码的一些挖,但我无法找到一个简单的方法。
问题是,上面的链接视图类的成员,它的实例,它需要一定的环境和路线图(我不希望被处理,我不应该这样)。 另外,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自己的实例。 必须有一个更简单的方法。
您可以创建网址助手像这里面的HTML辅助扩展方法:
var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
var url = urlHelper.Action("Home", "Index")
您也可以通过链接UrlHelper
公共的和静态类:
UrlHelper.GenerateUrl(null, actionName, controllerName, null, null, null, routeValues, htmlHelper.RouteCollection, htmlHelper.ViewContext.RequestContext, true)
在这个例子中,你不必创建新UrlHelper类,这可能是一个小的优势。
这里是让我的小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];
}
}
使用它作为:
public static MvcHtmlString RenderManagePrintLink(this HtmlHelper helper, )
{
var url = htmlHelper.UrlHelper().RouteUrl('routeName');
//...
}
(我张贴这只是ANS以供参考)