MVC - 由于ViewModel导致的外键错误?

时间:2017-04-04 09:59:05

标签: asp.net-mvc-4 viewmodel foreign-key-relationship

我正在创建Employee Class的View Model并使用EmployeeViewModel强力输入我的Create View。将来,我将在View Model中添加许多类。但问题是我遇到性别外键错误。可能是我在Create Controller中绑定了错误的值。以下是我的代码:

创建控制器:

public ActionResult Create()
{
  ViewBag.GenderId = new SelectList(db.Genders, "Id", "Name");
  return View();
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(EmployeeViewModel employeeModel)
{
  if (ModelState.IsValid)
  {
     db.Employees.Add(employeeModel.Employee);
     db.SaveChanges();
     return RedirectToAction("Index");
  }

  ViewBag.GenderId = new SelectList(db.Genders, "Id", "Name", employeeModel.Employee.GenderId);
  return View(employeeModel);
}

创建视图:

@model WebApplication2.EmployeeViewModel

@using (Html.BeginForm()) 
{

@Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>Employee</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.Employee.Name, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Employee.Name, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Employee.Name, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Employee.GenderId, "GenderId", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("GenderId", null, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.Employee.GenderId, "", 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" />
        </div>
    </div>
</div>
}

型号:

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public byte GenderId { get; set; }
    public Gender Gender { get; set; }
}
public class Gender {
    public byte Id { get; set; }
    public string Name { get; set; }
}

查看型号:

public class EmployeeViewModel
{
    public Employee Employee { get; set; }
}

0 个答案:

没有答案