来自ModelState的错误消息未得到本地化

时间:2013-02-27 14:30:23

标签: asp.net-mvc-3 localization globalization modelstate

我正在使用mvc4中的应用程序。我希望应用程序能够用英语和俄语工作。我有俄语标题,但错误信息仍然是英文。

我的模型包含: -

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

如果(ModelState.IsValid)变为false,它将转到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;
    }

但我总是得到英文错误信息。如何自定义代码以获得当前的文化。

1 个答案:

答案 0 :(得分:3)

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

要实现这一点,您应该在执行管道中更早地设置文化。例如,您可以在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);
}
相关问题