页面加载时,我的日期控件始终为空。 这是为什么? 数据库中有该控件的数据。
<div class="form-group">
@Html.LabelFor(model => model.StartDate, new { @class = "control- label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.StartDate, new { type = "Date" })
@Html.ValidationMessageFor(model => model.StartDate)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.EndDate, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.EndDate, new { type = "Date" })
@Html.ValidationMessageFor(model => model.EndDate)
</div>
</div>
答案 0 :(得分:-1)
正如@Coulton所述,确保在呈现页面之前,实际上是在控制器上填充模型的StartDate
和EndDate
属性。此外,如果您在班级上使用[DataType(DataType.Date)]
标记,则可以放弃TextBoxFor
帮助程序,而是使用EditorFor
帮助程序。
在Create或Edit视图之前填充数据属性的示例(这似乎是您尝试在那里构建的视图):
Controller.cs,ganho.Data
是一个带有[DataType(DataType.Date)]
标志
[HttpGet]
public ActionResult Edit(int? id)
{
// Omitted code
var result = from ganho in db.Ganhos
where ganho.GanhoID == id.Value
where ganho.Usuario.Id == user.Id
select new GanhoEditViewModel
{
GanhoID = ganho.GanhoID,
Valor = ganho.Valor,
Comentario = ganho.Comentario,
Data = ganho.Data,
Descricao = ganho.Descricao,
Tipo = ganho.Tipo
};
if (result.Count() < 1)
{
// 404, no such item exists
return HttpNotFound();
}
return View(result.Single());
}
Edit.chtml
<!-- Hidden Code, not relevant to the question -->
<div class="form-group">
@Html.LabelFor(model => model.Data, htmlAttributes: new { @class = "control-label col-md-2"})
<div class="col-md-10">
@Html.EditorFor(model => model.Data, new { htmlAttributes = new { @class = "form-control", @id = "dataInput"} })
@Html.ValidationMessageFor(model => model.Data, "", new { @class = "text-danger"})
</div>
</div>
如果您正在设置创建视图,可以像这样初始化字段:
Controller.cs,ganho.Data
是我的DateTime属性,用户将显示占位符数据。
[HttpGet]
public ActionResult Create()
{
var model = new Ganho()
{
// ...
Data = DateTime.Now, // Using the current date and time as a placeholder
// ...
};
return View(model);
}
请注意,在所有示例中,我都使用Strongy Typed视图!