gpt4 book ai didi

validation - 非美国日期格式的 ASP.NET MVC2 模型验证失败

转载 作者:行者123 更新时间:2023-12-04 15:37:43 24 4
gpt4 key购买 nike

我有一个小型 MVC2 应用程序,它以两种文化显示:en-US 和 es-MX。其中一部分包含用户输入的日期,该日期预先填充了模型中的当前日期。

使用 en-US 时,日期字段显示为 MM/dd/yyyy,可以使用相同的格式进行更改,而不会导致任何验证错误。

使用 es-MX 时,日期字段显示为 dd/MM/yyyy,但是当以这种格式编辑日期时,服务器端验证失败并显示消息:

The value '17/05/1991' is not valid for The Date.



关于该消息,我首先想到的一件事是它没有本地化。消息本身(我认为我无法控制)和字段的显示名称(我可以控制并在我的代码中进行了本地化)。应该以本地化格式显示。

我尝试单步执行代码以查看验证失败的确切位置,但它似乎发生在一些我看不到的已编译 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; }
}

示例 Controller 操作代码:
[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>

最佳答案

这是我在我的案例中解决问题的方法。我手动验证了 Controller 中的日期并重置了该属性的 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);
}

关于validation - 非美国日期格式的 ASP.NET MVC2 模型验证失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2851758/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com