Global functions in razor view engine

坚强是说给别人听的谎言 提交于 2019-12-23 17:48:35

问题


I want to have a global method like w in my razor view engine for localization my MVC application. I tried

@functions{
    public string w(string message)
    {
        return VCBox.Helpers.Localization.w(message);
    }
}

but I should have this in my every razor pages and I don't want that. I want to know how can I have a global function that can be used in every pages of my project?


回答1:


How about an extension method:

namespace System
{    
    public static class Extensions
    {
        public static string w(this string message)
        {
            return VCBox.Helpers.Localization.w(message);  
        }
    }
}

Called like so:

"mymessage".w();

Or:

string mymessage = "mymessage";
mymessage.w();

Or:

Extensions.w("mymessage");



回答2:


You can extend the HtmlHelper:

Extensions:

public static class HtmlHelperExtensions
{
    public static MvcHtmlString W(this HtmlHelper htmlHelper, string message)
    {
        return VCBox.Helpers.Localization.w(message);
    }
}

Cshtml:

@Html.W("message")


来源:https://stackoverflow.com/questions/12204410/global-functions-in-razor-view-engine

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