问题描述
类似于Datetime field in MVC Entity Framework,但不完全相同。他们的解决方案也没有解决我的问题。我有一个包含种子数据和以下内容的分贝,
具有可为空的DateTime属性的模型:
[DataType(DataType.Time)]
[displayFormat(DataFormatString = "{0:hh:mm tt}",ApplyFormatInEditMode = true)]
[display(Name = "Evening Showtime")]
public DateTime? ShowtimeEve { get; set; }
名为Productions.cshtml
的Razor Pages视图:
@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的继承将数据传递到View(这是代码优先项目):
[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,但是在那之后迷路了。
解决方法
我会给你一些建议,问题应该是其中之一。
更改日期时间格式,例如
DataFormatString = "{0:hh:mm}"
当我看着你采取行动时,我注意到你正在使用实体,但是 您的视图页面模型是一个模型。您应该将实体数据转换为 您的模型,然后返回您的视图页面模型。但是你的模型和 实体是同一个类,这不应该是问题。例如您的动作;
[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();
}
else
{
var productionModel = new Production();//TheatreCMS.Models.Production
productionModel.ShowtimeEve = production.ShowtimeEve;
//other converts here
}
return View(productionModel);
}
我的其他建议,请尝试在视图中使用此代码;
@Html.TextBoxFor(m => m.ShowtimeEve,new { @class = "form-control" })
,
我能够找到答案。我使这个问题复杂化了。尽管每个人都提供了很好的答案和见解,但真正的问题是HTML5问题以及value属性如何发送到视图。表单输入标签上的value属性的格式必须在24小时内。格式,而不是12小时。
因此只需更改:
cycle
到
[DisplayFormat(DataFormatString = "{0:hh:mm tt}",ApplyFormatInEditMode = true)]
发送到生产的“编辑视图”的输入元素的值现在在24小时内呈现。格式,使时间选择器可以正确地重新格式化为12小时。视图。
感谢大家的帮助。我是C#的新手,更不用说ASP.NET Entity MVC了,因此非常感谢您的支持。