生成的HTML帮助URL [英] Generate URL in HTML helper

查看:200
本文介绍了生成的HTML帮助URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常在ASP.NET视图人们可以使用下面的函数来获取URL(不是< A>

Normally in an ASP.NET view one could use the following function to obtain a URL (not an <a>):

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

不过,我找不到如何从一个自定义的HTML帮助做到这一点。我有

However, I cannot find how to do it from a custom HTML helper. I have

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

助手变量的作用和GenerateLink方法,但它们产生&LT; A&GT; 的。我做了一些挖了ASP.NET MVC源$ C ​​$ C,但我无法找到一个简单的方法。

The helper variable has the Action and GenerateLink methods, but they generate <a>’s. I did some digging in the ASP.NET MVC source code, but I could not find a straightforward way.

问题是,上面的链接视图类的成员,并为其实例化它需要一些背景和路线图(我不希望被处理,我不应该这样)。另外,HtmlHelper类的实例也有一些情况下,我认为是的URL实例的上下文信息子集的任一夜宵(而我又不想用它处理)。

The problem is that the Url above is a member of the view class and for its instantiation it needs some contexts and route maps (which I don’t want to be dealing with and I’m not supposed to anyway). Alternatively, the instance of the HtmlHelper class has also some context which I assume is either supper of subset of the context information of the Url instance (but again I don’t want to dealing with it).

综上所述,我认为这是可能的,但因为我可以看到所有的方式,涉及到一些处理一些或多或少的内部ASP.NET的东西,我不知道是否有更好的办法。

In summary, I think it is possible but since all ways I could see, involve some manipulation with some more or less internal ASP.NET stuff, I wonder whether there is a better way.

编辑:举例来说,一种可能性我看应该是:

For instance, one possibility I see would be:

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

但它似乎并不正确。我不希望被处理UrlHelper自己的实例。必须有一个更简单的方法。

But it does not seem right. I don't want to be dealing with instances of UrlHelper myself. There must be an easier way.

推荐答案

您可以创建网址助手像这里面的HTML帮助扩展方法:

You can create url helper like this inside html helper extension method:

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

这篇关于生成的HTML帮助URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆