我有这个问题,我的项目实体中有 2 个属性:
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "dd/MM/yyyy", ApplyFormatInEditMode = true)]
public DateTime? StartDate { get; set; }
[DisplayFormat(DataFormatString = "dd/MM/yyyy", ApplyFormatInEditMode = true)]
[DataType(DataType.Date)]
public DateTime EndDate { get; set; }
在我看来,我有以下代码。
<div class="control-group">
<label class="control-label" for="prependedInput">@Resources.Project.StartDate</label>
<div class="controls">
<div class="input-prepend">
<input type="text" name="StartDate" class="input-small datepicker" value="@DateTime.Now.ToDateFormat()" />
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="prependedInput">@Resources.Project.EndDate</label>
<div class="controls">
<div class="input-prepend">
<input type="text" name="EndDate" class="input-small datepicker" value="@DateTime.Now.ToDateFormat()" />
</div>
</div>
</div>
在我的 Controller 中,我试图创建一个新对象,但 ModelState.IsValid 始终返回 false,因为 StartDate 具有空值。
public virtual ActionResult Create(Project model)
{
if (ModelState.IsValid)
{
Repository.Project.Add(model);
return RedirectToAction(MVC.Project.Index());
}
return View(model);
}
我如何解决这个问题并将我的可为空的 StartDate 属性的值设置为使用日期选择器选择的日期?
最佳答案
DisplayFormat
属性在绑定(bind)数据时对 DateTime?
没有影响。由于此默认数据绑定(bind)器期望日期采用标准格式 f.e. YYYY-MM-dd
。
如果您想以不同的格式绑定(bind)日期时间,请使用自定义数据绑定(bind)器。您可以在这里找到解决方案:
http://blog.greatrexpectations.com/2013/01/10/custom-date-formats-and-the-mvc-model-binder/
它应该能完美解决您的问题。
关于c# - 可空日期时间的日期选择器绑定(bind)不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23149805/