所以我有这个视图应该返回一个名字和两个日期,但日期似乎总是为空。
我将一个警告绑定到创建按钮以查看js将从输入字段读取的日期,并且它总是正确的,但是当返回到post操作时,该对象在StartedOn和FinishedOn上始终具有空值(如果它们是约会?如果不是它给了我01/01/2001作为日期,当我尝试将其保存在数据库中时它抛出异常"将datetime2数据类型转换为日期时间数据类型导致了范围值")。
我的问题是,如果可以为空,为什么它总是返回null;如果没有,为什么它会返回01/01/2001?如何修复它?
我的观点:
@model Data.Project
@{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Project</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.StartedOn, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.StartedOn, new { htmlAttributes = new {@class = "form-control",type="date" } })
@Html.ValidationMessageFor(model => model.StartedOn, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.FinishedOn, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.FinishedOn, new { htmlAttributes = new {@class = "form-control" , type = "date" } })
@Html.ValidationMessageFor(model => model.FinishedOn, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" id="11" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section scripts{
<script>
$(function () {
$("#11").on("click",function() {
alert($("#StartedOn").val());
})
})
</script>
}
我的行动(此处的日期为全部为空)
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Name")] Project project)
{
if (ModelState.IsValid)
{
UtilityContext.AddProject(project);
UtilityContext.SaveChanges();
return RedirectToAction("Index");
}
return View(project);
}
我的模特:
public class Project
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public DateTime? StartedOn { get; set; }
public DateTime? FinishedOn { get; set; }
[ForeignKey("ProjectId")]
public virtual ICollection<Employee> EmployeesOnIt { get; set; }
}
答案 0 :(得分:2)
对象在StartedOn和FinishedOn上始终具有空值
因为你告诉它不来绑定这些值:
[Bind(Include = "Id,Name")] Project project
也许你应该绑定它们:
[Bind(Include = "Id,Name,StartedOn,FinishedOn")] Project project