如何从HtmlHelper类调用Url.Action?

Jus*_*tin 2 asp.net-mvc html-helper

我用过

Url.Action("actionFoo", "controllerBar")
Run Code Online (Sandbox Code Playgroud)

在我的观点(aspx).但是现在我正在将我的一些标记重构为我创建的HtmlHelper.

问题是我似乎没有包含正确的命名空间,或者View有一些我不知道的默认对象引用.点是编译器找不到Url.Action.

为简单起见,这里是我要做的......

public static MvcHtmlString RenderActionButtons(this HtmlHelper helper, string actionName, string controllerName)
{
    TagBuilder customActionButtonTagBuilder = new TagBuilder("a");
    customActionButtonTagBuilder.Attributes.Add(new KeyValuePair<string, string>("href", Url.Action(actionName, controllerName)));
    customActionButtonTagBuilder.InnerHtml = "foo";
    customActionButtonTagBuilder.AddCssClass("custom-action-button");

    return MvcHtmlString.Create(customActionButtonTagBuilder.ToString(TagRenderMode.Normal));
}
Run Code Online (Sandbox Code Playgroud)

如何将代码指向正确使用Url.Action?

Jus*_*tin 12

soltion ... Url是UrlHelper的一部分.如果你有HtmlHelper,你可以获得UrlHelper的实例,如下所示......

new UrlHelper(helper.ViewContext.RequestContext)
Run Code Online (Sandbox Code Playgroud)

这是暴露url.Action的对象