我在我的JQueryUI MVC 5项目中使用了ASP.NET数据报警器。我希望用户在创建和编辑视图中输入mm/dd/yy格式的日期。这就是我到目前为止所取得的成就:
这是我的模型:
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString =
"{0:MM-dd-yyyy}",
ApplyFormatInEditMode = true)]
public DateTime ProjectDeadline { get; set; }
这是jQuery在_Layout.cshtml中的代码:
<script type="text/javascript">
$(function () {
$('.date-picker').datepicker({ dateFormat: "MM-dd-yy" });
})
</script>
在“创建视图”中,我有以下内容:
在“编辑视图”中,我有以下内容:
如果我不点击“编辑”中的“约会”并点击“保存”,我会收到一个警告:
字段ProjectDeadline必须是日期。
我尝试了很多方法来得到我想要的,但这是我所能得到的最好的。我的大部分尝试都犯了错误。您能告诉我如何修正我的代码,使mm/dd/yyyy格式在日期字段中正确吗?谢谢。
发布于 2015-12-04 09:13:16
我已经多次遇到这个问题,但是我已经提出了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);
}
}
在应用程序启动时,将其连接起来:
ModelBinders.Binders.Add(typeof(DateTime?), new CustomDateTimeModelBinder());
发布于 2015-12-04 09:07:34
请尝试div datepicker中的数据-日期-格式=‘mm’:
div class="input-group date date-picker" data-date-format="yyyy-mm-dd">
@Html.EditorFor(model => model.ProjectDeadline, new { htmlAttributes = new { @class = "form-control", @maxlength = "10"} })
...
/div>
https://stackoverflow.com/questions/34084103
复制相似问题