如何从HtmlHelper类调用Url.Action?

时间:2010-11-24 22:11:47

标签: asp.net-mvc html-helper

我用过

Url.Action("actionFoo", "controllerBar")

在我的视图(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));
}

如何指出我的代码正确使用Url.Action?

1 个答案:

答案 0 :(得分:12)

soltion ... Url是UrlHelper的一部分。如果您拥有HtmlHelper,则可以获取UrlHelper的实例,如下所示......

new UrlHelper(helper.ViewContext.RequestContext)

这是暴露url.Action

的对象