Reputation: 4009
I am learning asp.net MVC so I do not have so much experience. I want to localize text on one page but I don’t want put labels to view model. Too much text must be localized and it does not look right to put all text in view model properties.
I would like to read localized value with razor directly from resource file. Is this possible? In what folder should I create resource file? How should I name resource file? How to read value at page from resource file?
Upvotes: 2
Views: 2350
Reputation: 67148
It's not different from what you would do in plain C# code. A detailed description (even if it's not about Razor same concepts still apply) can be found in this article.
First of all you have to decide where you want to put your resource files. Elective place is Resources folder. Alex suggests (and it's pretty reasonable) to mimic solution structure (views, model and controllers) there to keep things organized and tidy. In practice you'll have a structure like this:
. /Resources /Models LogInModel.resx /Controllers LogIn.resx /Views /Home LogIn.resx Index.resx
and so on. Localized resources will be simply used like this:
Views
<head>
<title>@MyProject.Resources.Views.Home.Index.Title</title>
</head>
<body>
<h1>@MyProject.Resources.Views.Home.Index.Welcome</h1>
</body>
Models
[Required(ErrorMessageResourceName = "Required",
ErrorMessageResourceType = typeof(MyProject.Resources.Models.LogIn))]
[ValidatePasswordLength(ErrorMessageResourceName = "PasswordMinLength",
ErrorMessageResourceType = typeof(MyProject.Resources.Models.LogIn))]
[DataType(DataType.Password)]
[DisplayName("Password")]
public string Password { get; set; }
Controllers
var user = FindUserByName(userName);
if (user == User.Nobody)
ModelState.AddModelError("1", MyProject.Resources.Controllers.Search.UserNotFound);
Now let's enable localization (which may be different for each thread then for its request). This is just an example, please refer to full article for all details:
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
if (HttpContext.Current.Session != null)
{
string name = (CultureInfo)this.Session["Culture"];
if (!String.IsNullOrEmpty(name))
{
CultureInfo ci = new CultureInfo(name );
Thread.CurrentThread.CurrentUICulture = ci;
Thread.CurrentThread.CurrentCulture =
CultureInfo.CreateSpecificCulture(ci.Name);
}
}
}
Upvotes: 4