jas*_*son 1 asp.net asp.net-mvc jquery date asp.net-mvc-5
我在ASP.NET MVC 5项目中使用JQueryUI Datepicker.我希望用户在"创建"和"编辑"视图中以mm/dd/yy格式输入日期.这是我迄今为止所取得的成就:
这是我的模特:
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString =
"{0:MM-dd-yyyy}",
ApplyFormatInEditMode = true)]
public DateTime ProjectDeadline { get; set; }
Run Code Online (Sandbox Code Playgroud)
这是_Layout.cshtml中的jQuery代码:
<script type="text/javascript">
$(function () {
$('.date-picker').datepicker({ dateFormat: "MM-dd-yy" });
})
</script>
Run Code Online (Sandbox Code Playgroud)
如果我没有在编辑中触摸日期并点击保存,我会收到警告:
ProjectDeadline字段必须是日期.
我尝试了许多可能性来获得我想要的东西,但这是我能得到的最好的东西.我在大多数尝试中都遇到了错误.你能告诉我如何修复我的代码以正确地在日期字段中获取mm/dd/yyyy格式吗?谢谢.
我已经多次遇到过这个问题,但是我已经想出了CustomDateTimeModelBinder查看DisplayFormat属性并将其绑定到模型的内容:
// <summary>
/// This makes the model binder able to find a custom datetime format
/// </summary>
public class CustomDateTimeModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (!String.IsNullOrEmpty(displayFormat) && value != null)
{
DateTime date;
displayFormat = displayFormat.Replace("{0:", String.Empty).Replace("}", String.Empty);
if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
return date;
}
bindingContext.ModelState.AddModelError(bindingContext.ModelName, String.Format("{0} is an invalid date format", value.AttemptedValue));
}
return base.BindModel(controllerContext, bindingContext);
}
}
Run Code Online (Sandbox Code Playgroud)
在您的应用程序启动中,连接它:
ModelBinders.Binders.Add(typeof(DateTime?), new CustomDateTimeModelBinder());