如何使用自定义格式的jQuery UI DatePicker和MVC 4(dd.MM.yyyy)

假设你想使用自定义罗马尼亚格式的datepicker:dd.MM.yyyy

如何在不遇到jqueryvalidation问题和错误解释回发后的日期时间的情况下如何做到这一点?

首先包括jquery-ui.js之后的datepicker-ro.js。

之后在模型中设置格式如下:

public class ProductionCalculationReportModel { [DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}", ApplyFormatInEditMode = true)] public DateTime? BeginDate { get; set; } [DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}", ApplyFormatInEditMode = true)] public DateTime? EndDate { get; set; } } 

然后,在.cshtml文件中,您可以放置​​文本框:

 @Html.TextBoxFor(x => x.BeginDate, "{0:dd.MM.yyyy}", new { @class = "datefield" }) @Html.TextBoxFor(x => x.EndDate, "{0:dd.MM.yyyy}", new { @class = "datefield" }) 

然后,在cshtml文件中,让我们来处理validation:

  

之后创建一个模型绑定器:

 public class ProductionCalculationReportModelBinder : DefaultModelBinder { protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) { if (propertyDescriptor.ComponentType == typeof(PAS.Areas.Admin.Models.ProductionCalculationReportModel)) { if (propertyDescriptor.Name == "BeginDate") { var obj = bindingContext.ValueProvider.GetValue("BeginDate"); return DateTime.ParseExact(obj.AttemptedValue.ToString(), "dd.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture); } if (propertyDescriptor.Name == "EndDate") { var obj = bindingContext.ValueProvider.GetValue("EndDate"); return DateTime.ParseExact(obj.AttemptedValue.ToString(), "dd.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture); } } return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder); } } 

像这样在Global.asax中添加它:

 ModelBinders.Binders.Add(typeof(ProductionCalculationReportModel), new ProductionCalculationReportModelBinder()); 

然后像这样使用它:

 [HttpPost] public ActionResult Index([ModelBinder(typeof(ProductionCalculationReportModelBinder))]ProductionCalculationReportModel model) {}