Call one Razor helper from another

2019-07-03 02:52发布

问题:

I need to create the second overload of Razor helper and want to call one helper from another (with some specific parameters). Is there any way to implement it?

回答1:

Sure:

using System.Web.Mvc;
using System.Web.Mvc.Html;

public static class ActionLinkExtensions
{
    public static IHtmlString MyActionLink(this HtmlHelper html)
    {
        // call the base ActionLink helper:
        return html.ActionLink("some text", "someAction");
    }
}

and then in your view:

@Html.MyActionLink()

If you are talking about @helper Razor helpers you need to pass an instance of the HtmlHelper as argument because it is not available in the helper context:

@helper MyActionLink(HtmlHelper html)
{
    @html.ActionLink("some text", "someAction")
}

and then:

@MyActionLink(Html)

Personally I prefer the first approach as it is view engine agnostic and can be ported across any other view engines you like whereas the second is Razor specific and if tomorrow Microsoft invent the Blade view engine you will have to rewrite much of your code.