【发布时间】:2010-05-25 11:23:20
【问题描述】:
我有一个小型 MVC2 应用程序,它以两种文化显示:en-US 和 es-MX。其中一部分包含用户输入的日期,该日期预先填充了模型中的当前日期。
使用 en-US 时,日期字段显示为 MM/dd/yyyy,并且可以使用相同的格式进行更改而不会导致任何验证错误。
在使用es-MX时,日期字段显示为dd/MM/yyyy,但是当以这种格式编辑日期时,服务器端验证失败并提示:
值“17/05/1991”对于日期无效。
关于该消息的第一件事是它没有本地化。消息本身(我认为我无法控制)和字段的显示名称(我可以控制并在我的代码中本地化)。应该以本地化格式显示。
我已尝试单步执行代码以查看验证失败的确切位置,但它似乎发生在一些我看不到的已编译 MVC 或 DataAnnotations 代码中。
应用详情:IIS6、ASP.NET 3.5 (C#)、MVC 2 RTM
示例型号代码:
public class TestVieModel{
[LocalizedDisplayNameDisplayName("TheDateDisplayName", NameResourceType=typeof(Resources.Model.TestViewModel))]
[Required(ErrorMessageResourceName="TheDateValidationMessageRequired", ErrorMessageResourceType=typeof(Resources.Model.TestViewModel))]
[DataType(DataType.Date)]
public DateTime TheDate { get; set; }
}
示例控制器操作代码:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Save(TestViewModel model) {
if(ModelState.IsValid) { // <--- Always is false when using es-MX and a date foramtted as dd/MM/yyyy.
// Do other stuff
return this.View("Complete", model);
}
// Validation failed, redisplay the form.
return this.View("Enter", model);
}
示例查看代码:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<HispanicSweeps.Web.Model.LosMets.EnterViewModel>" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Test</title>
</head>
<body>
<% using (Html.BeginForm()) {%>
<%= Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%= Html.LabelFor(model => model.TheDate) %>
</div>
<div class="editor-field">
<%= Html.EditorFor(model => model.TheDate) %>
<%= Html.ValidationMessageFor(model => model.TheDate) %>
</div>
<p><input type="submit" value="Save" /></p>
</fieldset>
<% } %>
</body>
</html>
【问题讨论】:
标签: validation localization asp.net-mvc-2 data-annotations