Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do localization for contents coming from @Html.LabelFor() in mvc3

I am just extending my this question a bit.

I have my App_LocalResources in my MVC web application (I don't have it in separate dll).

I have a my Model in different assembly. In the Model I have 2 classes Country and City:

public class Country: MyContainer
{
    public City city {get;set;}
} 

public class City
{
    public CityName {get;set;}
}

public class MyContainer
{
    public Cid {get;set;}
}

So in my action method I create and pass an object of country as my viewmodel.

And in the view I use this:

@Html.LabelFor(mdl=>mdl.City.CityName)
@Html.LabelFor(mdl=>mdl.Cid)

So this works well and label with text are rendered in English.

But how do I modify this so that it reads the text from my Resource files in my web application?

like image 405
thinkmmk Avatar asked Mar 15 '12 15:03

thinkmmk


People also ask

What does HTML Labelfor do?

The HTML <label> for Attribute is used to specify the type of form element a label is bound to. Attribute Values: It contains the value i.e element_id which specify the id of the element that the label is bound to.

What is@: in Razor?

Razor supports C# and uses the @ symbol to transition from HTML to C#. Razor evaluates C# expressions and renders them in the HTML output.

What is meaning of@: in. net mvc?

In MVC, @ is the respective char that allows you to use razor inside HTML (inside a . cshtml) which in runtime (or precompiled) will be converted to c#. With @ you may write C# within HTML and with @: you may write HTML within C#. Example: @foreach (TestClass item in Model) { @:@item.Code - @item.Name }


2 Answers

You could write a custom display attribute:

public class LocalizedDisplayNameAttribute : DisplayNameAttribute
{
    public LocalizedDisplayNameAttribute(string key): base(FormatMessage(key))
    {
    }

    private static string FormatMessage(string key)
    {
        // TODO: fetch the corresponding string from your resource file
        throw new NotImplementedException();
    }
}

and then:

public class City
{
    [LocalizedDisplayName("cityname")]
    public string CityName { get; set; }
}

You may also checkout the following localization guide. It provides a full implementation of a sample attribute.

like image 53
Darin Dimitrov Avatar answered Nov 15 '22 23:11

Darin Dimitrov


You can use [Display(ResourceType = typeof(App_LocalResources), Name = "AgreeTandCs")] where App_LocalResources is the name of the resource class (your .resx) and Name is the name of the static string you want to reference. Use LabelFor as usual in your view, and it will automagically pull in your resource.

In my example, the label displays the string stored with the variable name AgreeTandCs, and if you're viewing it in English it will be shown in the page as "I agree to these Terms and Conditions".

like image 34
pipedreambomb Avatar answered Nov 15 '22 21:11

pipedreambomb