Asp.net 为什么页面加载时我的日期控件为空?
页面加载时,“我的日期”控件始终为空。 为什么呢? 数据库中有该控件的数据Asp.net 为什么页面加载时我的日期控件为空?,asp.net,asp.net-mvc,datetime,datepicker,Asp.net,Asp.net Mvc,Datetime,Datepicker,页面加载时,“我的日期”控件始终为空。 为什么呢? 数据库中有该控件的数据 <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
<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>
@LabelFor(model=>model.StartDate,新的{@class=“control-label col-md-2”})
@Html.TextBoxFor(model=>model.StartDate,new{type=“Date”})
@Html.ValidationMessageFor(model=>model.StartDate)
@LabelFor(model=>model.EndDate,新的{@class=“controllabel col-md-2”})
@Html.TextBoxFor(model=>model.EndDate,新的{type=“Date”})
@Html.ValidationMessageFor(model=>model.EndDate)
如@Coulton所述,在呈现页面之前,确保您正在控制器上实际填充模型的StartDate
和EndDate
属性。另外,如果在类上使用[DataType(DataType.Date)]
标志,则可以放弃文本框for
帮助程序,而使用编辑器for
帮助程序
在创建或编辑视图之前填充数据属性的示例(这似乎是您试图在其中构建的视图):
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());
}
请注意,在所有示例中,我都使用Strongy类型的视图 您需要添加更多详细信息-控制器的代码和示例模型数据。您是否在控制器中为要传递到视图的模型填充StartDate?您将输入指定为
type=“date”
,这将呈现HTML5日期选择器(注意,它仅在Chrome中受支持),这意味着日期必须为ISO格式(yyyy-MM-dd
)。将[DisplayFormat]
属性添加到property@StephenMuecke:请不要在评论中提供答案。您对问题以及如何解决问题完全正确,但现在需要有人剽窃您的评论,否则此问题将无限期得不到答复。可能重复
<!-- 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>
[HttpGet]
public ActionResult Create()
{
var model = new Ganho()
{
// ...
Data = DateTime.Now, // Using the current date and time as a placeholder
// ...
};
return View(model);
}