我发现了许多simulair问题,但不是一个有效的干净解决方案.我看到很多自定义代码可以让它工作,但为什么会这样?这应该从一开始就不起作用吗?
我认为奇怪的是,在IE9中它可以工作,但在Firefox和Chrome中它失败了.
每当我在Firefox或Chrome中尝试时,我都会收到消息“字段生日必须是日期”.
当我在新的MVC 4 RTM项目中尝试下面的代码时,我无法让它工作.我在所有浏览器中都看到DateTime.Now默认为dd-MM-yyyy(Holland)但我无法在Firefox和Chrome中提交它.
全局标记未在web.config中设置,因此必须使用默认值.我来自荷兰,所以它应该得到我猜的客户文化.
public class RegisterModel { [required] [Display(Name = "User name")] public string UserName { get; set; } [required] [DisplayFormat(DataFormatString = "{0:d}",ApplyFormatInEditMode = true)] //[DataType(DataType.Date)] public DateTime Birthday { get; set; } } [AllowAnonymous] public ActionResult Register() { RegisterModel vm = new RegisterModel() { Birthday = DateTime.Now }; return View(vm); } [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public ActionResult Register(RegisterModel model) { if (ModelState.IsValid) { // Attempt to register the user try { //WebSecurity.CreateUserAndAccount(model.UserName,model.Password); //WebSecurity.Login(model.UserName,model.Password); return RedirectToAction("Index","Home"); } catch (MembershipCreateUserException e) { ModelState.AddModelError("",ErrorCodeToString(e.StatusCode)); } } // If we got this far,something Failed,redisplay form return View(model); }
<!-- language: lang-none --> @model DateTimeWithDatePicker.Models.RegisterModel @{ ViewBag.Title = "Register"; } <hgroup class="title"> <h1>@ViewBag.Title.</h1> <h2>Create a new account.</h2> </hgroup> @using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.ValidationSummary() <fieldset> <legend>Registration Form</legend> <ol> <li> @Html.LabelFor(m => m.UserName) @Html.TextBoxFor(m => m.UserName) </li> <li> @Html.LabelFor(m => m.Birthday) @Html.EditorFor(m => m.Birthday) </li> </ol> <input type="submit" value="Register" /> </fieldset> } @section Scripts { @Scripts.Render("~/bundles/jqueryval") }
解决方法
我能够通过修改日期的jQuery验证器函数来解决这个问题:
<script type="text/javascript"> $(function () { var dateFormat="dd/mm/yy"; // en-gb date format,substitute your own $("#Birthday").datepicker({ "dateFormat": dateFormat }); jQuery.validator.addMethod( 'date',function (value,element,params) { if (this.optional(element)) { return true; }; var result = false; try { $.datepicker.parseDate(dateFormat,value); result = true; } catch (err) { result = false; } return result; },'' ); });