gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:21:53 24 4
gpt4 key购买 nike

在我的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com