在培养改变后,验证错误消息不会改变

时间:2013-01-22 16:41:11

标签: asp.net-mvc c#-4.0 localization asp.net-mvc-4 currentuiculture

我目前正在开发一个需要支持2种语言的 MVC4 应用程序。 我在 DataAnnotations 中使用以下格式的资源:

public class SignupModel
{
    [Required(ErrorMessageResourceName = "Registration_ValidEmailRequired", ErrorMessageResourceType = typeof(Validation))]
    [Email(ErrorMessageResourceName = "Registration_ValidEmailRequired", ErrorMessageResourceType = typeof(Validation))]
    public string Email { get; set; }

    [Required(ErrorMessageResourceName = "Registration_PasswordRequired", ErrorMessageResourceType = typeof(Validation))]
    [StringLength(100, MinimumLength = 8, ErrorMessageResourceName = "Registration_PasswordInvalidLength", ErrorMessageResourceType = typeof(Validation))]
    [DataType(DataType.Password)]
    public string Password { get; set; }
}

我创建了一个全局操作过滤器,可以读取语言cookie(如果存在),并相应地设置当前的文化 uiculture 。如果cookie不存在,则使用当前文化创建cookie。这就是过滤器中 OnActionExecuting 的样子:

public void OnActionExecuting(ActionExecutingContext filterContext)
{
    var langCookie = GetOrSetLanguageCookie(filterContext.HttpContext);
    var culture = new CultureInfo(langCookie.Value);

    Thread.CurrentThread.CurrentCulture = culture;
    Thread.CurrentThread.CurrentUICulture = culture;
}

除非发生这种情况,否则一切都按预期工作:

  1. 从家庭控制器中的注册操作发布HTML表单(假设在家中没有客户端验证,因此没有任何关于其花哨布局的内容被打破)。
  2. 如果发布的数据有错误,则会以与当前文化相匹配的语言显示。 (很好,也很期待)。
  3. 使用客户端中启用的下拉菜单(实际发回服务器)来更改语言。 (我还没有实现 PRG 模式,所以我看到有关重新发布相同数据的警告。)
  4. 视图使用我选择的语言呈现,但验证消息仍保留与最初使用的语言相同。
  5. 如果我调试处理语言切换的动作过滤器,我可以看到ModelState用原始语言保存错误,所以我猜测验证只在服务器中发生一次。 我想我需要清理ModelState并强制验证,但我想知道这是否是一个hack以及是否有更好的方法来处理这个问题。

    谢谢! R上。

1 个答案:

答案 0 :(得分:1)

阅读Shaun Xu的帖子: http://geekswithblogs.net/shaunxu/archive/2010/05/06/localization-in-asp.net-mvc-ndash-3-days-investigation-1-day.aspx

ModelBinder(负责获取验证消息)在操作之前和操作过滤器之前运行,这就是为什么在确定验证消息文本之前发生文化更改并且不受其影响的原因。

您可以尝试将此代码移动到较早的扩展点,例如控制器的Execute或ControllerFactory的CreateController方法。

您可以在此处查看我提出的解决方案问题: How to control the language in which model validation errors are displayed

相关问题