【问题标题】:ASP.NET MVC2 Model Validation Fails with Non-US Date FormatASP.NET MVC2 模型验证因非美国日期格式而失败
【发布时间】: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


    【解决方案1】:

    以下是我解决问题的方法。我手动验证了控制器中的日期并重置了该属性的 ModelState:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Save(TestViewModel model) {
    
        var tempDate = new DateTime();
        var culture = CultureInfo.CurrentUICulture;
    
        if(DateTime.TryParse(Request.Form["TheDate"], culture, DateTimeStyles.None, out tempDate)) {
            model.DateOfBirth = tempDate;
            ModelState.Remove("TheDate");
            }
    
        if(ModelState.IsValid) {  // <--- Now valid
            // Do other stuff
            return this.View("Complete", model);
            }
    
        // Validation failed, redisplay the form.
        return this.View("Enter", model);
        }
    

    【讨论】:

      【解决方案2】:

      验证发生在 DataAnnotations 类中。您可以为自己的目的子类化 DataAnnotations 类。

      我将创建一个新的 MultiCultureDateType DataAnnotations 类,该类将验证跨多种文化的日期。

      更多信息:http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-12-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多