4

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?

ahmadali shafiee
  • 4,350
  • 12
  • 56
  • 91

2 Answers2

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")
andres descalzo
  • 14,887
  • 13
  • 64
  • 115
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");
Paul Fleming
  • 24,238
  • 8
  • 76
  • 113
  • as you see I can use `VCBox.Helpers.Localization.w(message);` but I need a better way! – ahmadali shafiee Aug 30 '12 at 19:56
  • @ahmadalishafiee. The shortest you're going to get will have a "." in it. How do you define "better way"? – Paul Fleming Aug 30 '12 at 20:00
  • I want something like `w` as Wordpress and other apps have. there is a `write` method to write something and now I want to have `w` to write but localized write. – ahmadali shafiee Aug 30 '12 at 20:02
  • Write the extension method against the ViewPage instead. `public static string w(this ViewPage view, string message){/* do stuff */}`. Then you should be able to do a straight `w("mymessage")`. – Paul Fleming Aug 30 '12 at 20:05
  • I tried it but compiler didn't find `w`. I also added `` into the `` section in `web.config` – ahmadali shafiee Aug 30 '12 at 20:17
  • Try removing the namespace completely from the extension class. – Paul Fleming Aug 30 '12 at 20:26
  • If you add an extension method to the viewpage you would still need to do `this.w("message")`. You are always going to need the `something.w("message")`. If you wan't short, best bet is string extension method and calling it as `"message".w()` – Paul Fleming Aug 30 '12 at 20:37