2013-02-27 81 views
1

我正在研究mvc4中的应用程序。我希望应用程序能够以英语和俄语工作。我以俄语获得了标题,但错误消息仍然是英语。来自ModelState的错误消息未得到本地化

我的模型包含: -

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

如果(ModelState.IsValid)变为假就会去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; 
    } 

但我总是得到English.How错误消息我可以定制代码以获得当前文化。

回答

2

原因是因为你太晚设置文化。您正在将其设置在控制器操作中,但验证消息已经比控制器操作早得多地被模型绑定器添加,甚至开始执行。在那个阶段,当前的线程文化仍然是默认的。

为了实现这个目标,您应该在执行管道中更早地设置文化。例如,你可以做到这一点的方法Application_BeginRequest在里面你Global.asax

就像这样:

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); 
}