我有一个视图,其中文本框绑定到日期时间模型字段。
风景:
@Html.TextBoxFor(model => model.StartDate, new { @class = "datepicker", id = "startDate" })
该模型:
[Required(ErrorMessageResourceType = typeof(Resources.ValidationMessages), ErrorMessageResourceName = "GeneralRequired")]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
[DataType(DataType.Date)]
[Display(Name = "StartDate", ResourceType = typeof(Resources.Something))]
public DateTime? StartDate { get; set; }
View 使用 jQuery datepicker 来处理日期输入。 Jquery 只生成日期,但据我所知,C# 中没有唯一的日期类型。
我还使用自定义 DateTime 模型绑定器,但它太大了,无法发布其代码 (tl;dr ;))。
例如,当用户在文本框中输入 15-01-2015 并将其发布到方法时,模型绑定器会将其正确转换为(转换为 15-01-2015 12:00)。问题是当验证被触发时,因为表单上有两个日期时间字段,如果用户仅输入其中之一,则操作方法将返回带有验证消息的视图。已输入的字段显然仍应填写。问题是,当控制器的操作方法返回视图时,它会将日期时间放入文本框中,而不仅仅是日期。
我们是否可以使用任何方法仅将日期而不是日期和时间传递到视图中的绑定字段?或者也许保留字段绑定但仅在文本框中显示 value.Date ?
EDIT:
我尝试应用 Hugo Delsing 的解决方案,但遇到了下一个问题。基本上我们将使用 EditorTemplate 作为模型的 DateTime 字段。 DateTime.cshtml 如下所示:
@model System.DateTime?
@if (Model == null)
{
@Html.TextBox(
string.Empty,
"",
new { @class = "datepicker", @type = "text" })
}
else
{
@Html.TextBox(
string.Empty,
Model.ToString("dd-MM-yyyy"),
new { @class = "datepicker", @type = "text" })
}
据我了解,问题出现在该行
Model.ToString("dd-MM-yyyy")
因为抛出的错误是
Shared\EditorTemplates\DateTime.cshtml(13):错误 CS1501:无重载
for 方法 'ToString' 需要 1 个参数
据我了解,就像总是评估 else 一样,对吗?
有没有任何解决方案可以实现我想要的目标,而无需将 if 语句移至主视图并构建类似的内容?
@if(model.StartDate.HasValue)
{
@Html.EditorFor(model => model.StartDate, "TemplateFirst")
}
else
{
@Html.EditorFor(model => model.StartDate, "TemplateSecond")
}