Error messages from ModelState not get localized

寵の児 提交于 2019-12-08 07:33:17

问题


I am working on an application in mvc4.I want the application to work in English and Russian.I got titles in russian, but error messages are still in english.

My model contains:-

 [Required(ErrorMessageResourceType = typeof(ValidationStrings),
              ErrorMessageResourceName = "CountryNameReq")]            
    public string CountryName { get; set; }

if(ModelState.IsValid) becomes false it will go to GetErrorMessage()

public string GetErrorMessage()
    {  
       CultureInfo ci = new CultureInfo(Session["uiCulture"].ToString());

        System.Threading.Thread.CurrentThread.CurrentUICulture = ci;

        System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ci.Name);          
    string errorMsg = string.Empty;
    int cnt = 1;
    var errorList = (from item in ModelState
                   where item.Value.Errors.Any()
                   select item.Value.Errors[0].ErrorMessage).ToList();                                                 

        foreach (var item in errorList)
        {
            errorMsg += cnt.ToString() + ". " + item + "</br>";
            cnt++;
        }
        return errorMsg;
    }

But i always get error message in English.How can i customize the code to get current culture.


回答1:


The reason for that is because you are setting the culture too late. You are setting it inside the controller action, but the validation messages were added by the model binder much earlier than your controller action even started to execute. And at that stage the current thread culture was still the default one.

To achieve that you should set the culture much earlier in the execution pipeline. For example you could do that inside the Application_BeginRequest method in your Global.asax

Just like that:

protected void Application_BeginRequest(object sender, EventArgs e)
{
    CultureInfo ci = new CultureInfo(Session["uiCulture"].ToString());
    System.Threading.Thread.CurrentThread.CurrentUICulture = ci;
    System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ci.Name);
}


来源:https://stackoverflow.com/questions/15114582/error-messages-from-modelstate-not-get-localized

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!