c# - 我的 Nullable DateTime View 因 Null 而失败

标签 c# asp.net-mvc datetime

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

@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,我会收到以下消息:

The model item passed into the dictionary is null, but this dictionary requires a non-null model item of type 'System.DateTime'.

在模型 ProfileEdit 中,我将字段定义如下:

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

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

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

更新:

这是 Controller 操作(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);
}

最佳答案

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

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

特别是数据类型,因为它是 Date 而不是像我的模板那样的 DateTime

关于c# - 我的 Nullable DateTime View 因 Null 而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37012520/

相关文章:

c# - 跨AppDomains时无法将对象类型转换为目标类型

c# - 从Elastic脚本参数循环遍历数组

c# - 我的 UWP 应用无法读取 txt 文件

c# - 服务层还是 Controller ?

c# - 如何让日期选择器不填充(其值为 null)?

asp.net-mvc - 为什么 Entity Framework 不初始化我的导航集合?

Python Pandas 日期时间索引

c# - 验证我的 DelegatingHandler 是否已添加到 IHttpClientBuilder

c# - 检查 datetime 实例是否落在其他两个 datetime 对象之间

R函数返回时间序列ts()对象的开始和结束日期?