可为null的DateTime的数据选择器绑定不正确



我有这个问题,我的项目实体中有两个属性:

    [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的值为null。

   public virtual ActionResult Create(Project model)
    {
        if (ModelState.IsValid)
        {
            Repository.Project.Add(model);
            return RedirectToAction(MVC.Project.Index());
        }
        return View(model);
    }

如何解决此问题并将可为null的StartDate属性的值设置为使用日期选择器选择的日期?

绑定数据时,

DisplayFormat属性对DateTime?没有影响。由于这个默认的数据绑定器期望日期是标准格式,例如YYYY-MM-dd

如果要以不同格式绑定日期时间,请使用自定义数据绑定器。你可以在这里找到解决方案:

http://blog.greatrexpectations.com/2013/01/10/custom-date-formats-and-the-mvc-model-binder/

它应该非常适合你的问题。

最新更新