Michael Kniskern
Michael Kniskern

Reputation: 25280

Map appropriate Resource (.resx) file in code - ASP.NET MVC

I have the following resource files in my ASP.NET MVC application to stored form validation error message for both English and Spanish

ErrorMessages.resx -- English Error Messages
ErrorMessages.sp.resx -- Spanish Error Messages

In my models that require the System.ComponentModel.DataAnnotations Required Attributes they are marked like this:

[Required(ErrorMessageResourceType = typeof(ErrorMessages), ErrorMessageResourceName)]
public string MyProperty { get; set; }

In my controller, I am reading a JavaScript cookie that contains the user's selected language on the site and programmatically set the 'CultureInfo' of the current thread and the HTTP session:

public ActionResult MyController() 
{
    var language = HttpContext.Request.Cookies["language"].Value;

    if(language.Equals("english")) 
    {
        HttpContext.Session["culture"] = "en-US";
        Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
    }
    else 
    {
        HttpContext.Session["culture"] = "es-US";
        Thread.CurrentThread.CurrentCulture = new CultureInfo("es-US");
    }
}  

How do I set the appropriate resource file once the CultureInfo value has been modified?

Upvotes: 1

Views: 1248

Answers (2)

Michael Kniskern
Michael Kniskern

Reputation: 25280

Using @Koryakinp suggestion, I modified the controller code to the following:

var language = HttpContext.Request.Cookies["language"].Value;

if(language.Equals("english"))
{
    HttpContext.Session["culture"] = "en-US";
    Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US");
}

Also, I had to restructure the .resx files. I created a .resx named "ErrorMessages" as the base .resx and renamed the existing .resx files:

ErrorMessages.resx
ErrorMessages.en-US.resx
ErrorMessages.es-US.resx

Upvotes: 1

koryakinp
koryakinp

Reputation: 4135

Spanish .resx file should be *.es.resx, not *.sp.resx.

In order to resolve translations from an appropriate .resx file you need to assign Thread.CurrentThread.CurrentUICulture, not Thread.CurrentThread.CurrentCulture

Upvotes: 1

Related Questions