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?
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.
Razor supports C# and uses the @ symbol to transition from HTML to C#. Razor evaluates C# expressions and renders them in the HTML output.
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 }
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.
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With