【问题标题】:Error messages from ModelState not get localized来自 ModelState 的错误消息未本地化
【发布时间】:2013-02-27 14:30:22
【问题描述】:

我正在开发 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;
    }

但我总是收到英文错误消息。如何自定义代码以获取当前文化。

【问题讨论】:

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


    【解决方案1】:

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

    要实现这一点,您应该在执行管道中更早地设置文化。例如,您可以在 Global.asax 中的 Application_BeginRequest 方法中执行此操作

    就这样:

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

    【讨论】: