这是我的模特;
using System;
using System.ComponentModel.DataAnnotations;
namespace thinkBigHR.Models
{
public class Shift
{
[Key]
public int Id { get; set; }
public DateTime Date { get; set; }
public Employee Employee { get; set; }
}
}
这是我的控制器;
// POST: Shifts/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Date, Employee")] Shift shift)
{
ClaimsIdentity user = User.Identity as ClaimsIdentity;
if (user.HasClaim("Administrator", "true"))
{
if (ModelState.IsValid)
{
db.Shifts.Add(shift);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(shift);
}
return new HttpStatusCodeResult(HttpStatusCode.Unauthorized);
}
这是我的观点。
@using thinkBigHR.Models;
@model thinkBigHR.Models.Shift
@{
ApplicationDbContext db = new ApplicationDbContext();
ViewBag.Title = "Create";
var employees = db.Employees.ToList();
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Shift</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Date, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<input type="datetime-local" class="form-control" id="Date" name="Date" />
@Html.ValidationMessageFor(model => model.Date, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Assigned Employee:</label>
<select name="Employee" class="form-control">
@foreach (var item in employees)
{
<option value="@item.Id" id="Employee">@item.LegalName (@item.JobTitle)</option>
}
</select>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
因此它正确地呈现视图,但是一旦数据返回到控制器,我就设置了断点,并且它显示仅传递了班次的日期,但没有选择任何Employee的详细信息(返回) as null)。
答案 0 :(得分:0)
这是因为ASP.NET MVC默认模型绑定器无法确定Shift的Employee成员中要存储的内容。
Employee是一个类,您需要创建名为它的成员的HTML控件:
<input name="Employee.LegalName" />
<input name="Employee.JobTitle" />
现在,在发布表单后,ASP.NET MVC模型绑定器将知道哪个输入字段属于Shift中Employee类的哪个成员。
Here you can find有关默认模型装订器的详细说明。