【问题标题】:My Nullable DateTime view is failing with a Null我的 Nullable DateTime 视图因 Null 而失败
【发布时间】:2016-05-03 19:12:02
【问题描述】:

在我的 MVC 应用程序中,我有一个共享的 DateTime.cshtml 视图,定义如下:

@model DateTime?
@{
    var value = "";
    if (Model.HasValue) 
    {
        value = String.Format("{0:d}", Model.Value);
    }
}
@Html.TextBox("", value, new { @class = "form-control datepicker", type = "text" })

在我的一个观点中,我是这样使用它的:

@model PublicationSystem.ViewModels.ProfileEdit
<div class="form-group">
    @Html.LabelFor(model => model.BirthDate, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.BirthDate)
    </div>
</div>

但是,如果我的模型的出生日期为 Null,我会收到以下消息:

传入字典的模型项为空,但此字典需要“System.DateTime”类型的非空模型项。

ProfileEdit 模型中,我有这样定义的字段:

[DataType(DataType.Date), Display(Name = "Birth Date")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? BirthDate { get; set; }

即使那里有 Null,我怎样才能让它加载视图?我做错了什么?

PS,我读过与此类似的其他帖子,其中大部分都说让我的编辑器控件的模型可以为空,但正如你所看到的,我已经这样做了。

更新:

这里是控制器操作(Mapper.Map 只是获取模型,并填充 ViewModel ProfileEdit):

[CheckId(RedirectToReferrer = true)]
public virtual ActionResult Edit(Guid id)
{
    var profileEdit = Mapper.Map<ProfileEdit>(db.Profile.Find(id));

    if (profileEdit == null)
    {
        return HttpNotFound();
    }

    return View(profileEdit);
}

【问题讨论】:

  • "传入字典的模型项为空,但此字典需要 'System.DateTime' 类型的非空模型项。"字典在哪里声明,如何声明?
  • 我不知道。也许 MVC 正在使用其他东西来呈现编辑器。
  • 我测试了你的模板,它没有任何错误。向我们展示发送视图的控制操作
  • 您是否尝试过删除 BirthDate 属性上的这些属性,并查看您查看渲染时是否没有错误?
  • 模板可以是简单的@model DateTime? @Html.TextBox("", "{0:d}", new { @class = "form-control datepicker" })(其他不需要)。如果您收到该错误,那是因为您正在调用另一个视图/模板,而不是您显示的那个

标签: c# asp.net-mvc datetime


【解决方案1】:

@Mangist 是对的。就是这个属性:

[DataType(DataType.Date), Display(Name = "Birth Date")]

具体来说,DataType,因为它是 Date 而不是 DateTime,就像我的模板所使用的那样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-09
    • 1970-01-01
    • 2015-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多