Call one Razor helper from another

懵懂的女人 提交于 2020-01-03 21:09:30

问题


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.



来源:https://stackoverflow.com/questions/7293068/call-one-razor-helper-from-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!