我有这个问题,我的项目实体中有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>
在我的控制器中,我正在尝试创建一个新对象,但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属性的值设置为使用datepicker选择的日期?
答案 0 :(得分:2)
DisplayFormat
属性对DateTime?
没有影响。由于此默认数据绑定器,因此期望日期为标准格式f.e. YYYY-MM-dd
。
如果要以不同格式绑定datetime,请使用自定义数据绑定器。你可以在这里找到解决方案:
http://blog.greatrexpectations.com/2013/01/10/custom-date-formats-and-the-mvc-model-binder/
它应该可以完美地解决您的问题。