我是asp.net mvc的新手
我在两个表中都有两个表tblEmployee和tblDepartment,常见字段是部门ID。 如果用户创建新员工,他们必须从tblDepartment表中选择他们的部门列表。我从该表中获得部门列表没有问题,但是当我提交表单时,离开的部分将无效进入数据库。
模型
public partial class Department
{
public Department()
{
this.tblEmployees = new HashSet<Employee>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Employee> tblEmployees { get; set; }
public Employee employee { get; set; }
}
public partial class Employee
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string City { get; set; }
public Nullable<int> DepartmentId { get; set; }
public virtual Department tblDepartment { get; set; }
public List<Department> deprtment { get; set; }
public virtual string Department { get; set; }
public bool available { get; set; }
}
控制器:
public ActionResult Create()
{
SampleDbContext Db = new SampleDbContext();
List<Employee> employees = Db.Employees.Include("tblDepartment").ToList();
ViewBag.list = new SelectList(Db.Departments, "Id", "Name");
return View();
}
[HttpPost]
public ActionResult Create( Employee employee)
{
SampleDbContext Db = new SampleDbContext();
if (ModelState.IsValid)
{
Db.Employees.Add(employee);
Db.SaveChanges();
return RedirectToAction("Index");
}
return View(employee);
}
查看:
@model EmployeeList.Models.Employee
....
@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.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>
.... // controls for other properties of Employee
<div class="form-group">
@Html.LabelFor(model => model.DepartmentId, "DepartmentId", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("list","select Depar")
@Html.ValidationMessageFor(model => model.DepartmentId, "", 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>
}