Ahmadali Shafiee
Ahmadali Shafiee

Reputation: 4657

Global functions in razor view engine

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?

Upvotes: 4

Views: 4805

Answers (2)

andres descalzo
andres descalzo

Reputation: 14967

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")

Upvotes: 2

Paul Fleming
Paul Fleming

Reputation: 24526

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

Upvotes: 1

Related Questions