【发布时间】:2020-08-27 05:03:14
【问题描述】:
类似于Datetime field in MVC Entity Framework,但不完全是。他们的解决方案也没有解决我的问题。我有一个带有种子数据的 dB 和以下内容,
具有可为空的 DateTime 属性的模型:
[DataType(DataType.Time)]
[DisplayFormat(DataFormatString = "{0:hh:mm tt}", ApplyFormatInEditMode = true)]
[Display(Name = "Evening Showtime")]
public DateTime? ShowtimeEve { get; set; }
名为 Productions.cshtml 的 Razor 页面视图:
@model TheatreCMS.Models.Production
@using TheatreCMS.Controllers
@{
ViewBag.Title = "Edit";
}
@Styles.Render("~/Content/Site.css")
<h2>Edit</h2>
@using (Html.BeginForm("Edit", "Productions", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="formContainer2">
<div class="form-horizontal">
<h4>Production</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.ProductionId)
<div class="form-group">
@Html.LabelFor(model => model.ShowtimeEve, htmlAttributes: new { @class = "control-label col-md-2 inputLabel" })
<div class="col-md-10 formBox">
@Html.EditorFor(model => model.ShowtimeEve, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ShowtimeEve, "", new { @class = "text-danger" })
</div>
</div>
}
还有一个控制器 ProductionsController.cs 使用 DBContext 的继承将数据传递给视图(这是一个代码优先项目):
[HttpGet]
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Production production = db.Productions.Find(id);
if (production == null)
{
return HttpNotFound();
}
return View(production);
}
视图上的表单不会填充创建的输入字段中的数据。它正在创建一个空白的时间选择器字段。我需要它是一个数据填充时间选择器字段。这是一个编辑视图,因此目标是让所有字段都填充数据,向客户展示他们将要更改的内容。
我一步一步地运行调试器,检查输出值。它正在将 DateTime 值从 Controller 传递给 View,但之后它在某处丢失了。
【问题讨论】:
-
渲染出来的 HTML 是什么样子的
-
我认为这是因为您声明的变量是
Datetime,而您强制指定的类型是Datatype.time -
@AbdulHaseeb 如果我没记错的话,
DataType.Time就像DataType.Date一样,是从基础DataType.Datetime继承而来的。至少对于[DataAnnotations],就是这样。我知道在 C# 中没有“时间”数据类型,至少本机没有。那只是 DateTime,然后用DateTime.ToString("hh:mm tt")格式化。 -
@Vince 原始 html 呈现为
<input class="form-control text-box single-line" id="ShowtimeEve" name="ShowtimeEve" type="time" value="05:30 PM">,但在将[DataAnnotation]中的{0:hh:mm tt}更改为{0:hh:mm}后,它以24 小时发送。格式化的时间,这是它所需要的,因此可以正确呈现<input class="form-control text-box single-line" id="ShowtimeEve" name="ShowtimeEve" type="time" value="05:30">。
标签: c# asp.net-mvc model-view-controller entity-framework-6 datetime-format