【问题标题】:How do I call Url.Action from an HtmlHelper class?如何从 HtmlHelper 类中调用 Url.Action?
【发布时间】:2011-05-15 09:26:17
【问题描述】:

我用过

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

在我的视图中 (aspx)。但现在我正在将我的一些标记重构为我创建的 HtmlHelper。

问题是我似乎没有包含正确的命名空间,或者视图有一些我不知道的默认对象引用。重点是编译器找不到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 的正确用法?

【问题讨论】:

标签: asp.net-mvc html-helper


【解决方案1】:

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

new UrlHelper(helper.ViewContext.RequestContext)

这是暴露 url.Action 的对象

【讨论】:

    猜你喜欢
    • 2020-05-14
    • 1970-01-01
    • 1970-01-01
    • 2014-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多