开发者

How do I call Url.Action from an HtmlHelper class?

开发者 https://www.devze.com 2023-01-27 00:50 出处:网络
I\'ve used Url.Action(\"actionFoo\", \"controllerBar\") in my Views (aspx).But now I\'m refactoring some of my markup to an HtmlHelper I\'ve created.

I've used

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

in my Views (aspx). But now I'm refactoring some of my markup to an HtmlHelper I've created.

Problem is I don't seem to have the proper namespaces included or the View has some default object reference that I'm not开发者_如何学Go aware of. Point is the compiler can't find Url.Action.

For simplicity sake here is what I'm trying to do...

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));
}

How do I point my code to the proper usage of Url.Action?


soltion... Url is part of a UrlHelper. You can obtain an instance of the UrlHelper if you have the HtmlHelper as follows...

new UrlHelper(helper.ViewContext.RequestContext)

this is the object that exposes url.Action

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号