模型:
教师班
[Key]
[Required(ErrorMessage="*Enter Faculty id")]
[StringLength(5)]
public string Id { get; set; }
[Required(ErrorMessage="*Enter First Name")]
[MaxLength(30)]
public string F_Name { get; set; }
[Required(ErrorMessage="*Enter Last Name")]
[MaxLength(30)]
public string L_Name { get; set; }
[MaxLength(30)]
public string M_Name { get; set; }
[Required(ErrorMessage="*Enter Email id")]
[MaxLength(50)]
public string Email{ get; set; }
[Required(ErrorMessage="*Enter Department")]
public Int16 Dept_Id { get; set; }
[ForeignKey("Dept_Id")]
public virtual Department Dept { get; set; }
部门类:
public class Department //static table
{
[Key]
public Int16 Id { get; set; }
[Required]
[MaxLength(20)]
public string Dept_Name { get; set; }
}
看法:
<div class="editor-label">
Faculty Id
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.Id, new { style = "width:200px;"})
@Html.ValidationMessageFor(model => model.Id,null, new { style="color:Red"})
</div>
<div class="editor-label">
First Name
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.F_Name,new { style = "width:200px;"})
@Html.ValidationMessageFor(model => model.F_Name, null, new { style="color:red;"})
</div>
<div class="editor-label">
Middle Name
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.M_Name,new { style = "width:200px;"})
@Html.ValidationMessageFor(model => model.M_Name)
</div>
<div class="editor-label">
Last Name
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.L_Name,new { style = "width:200px;"})
@Html.ValidationMessageFor(model => model.L_Name, null, new { style="color:red;"})
</div>
<div class="editor-label">
Department
</div>
<div class="editor-field">
@Html.DropDownListFor(model =>model.Dept_Id ,ViewBag.Dept_Id as IEnumerable<SelectListItem>,
string.Empty,new { style = "width:200px;text-align:center;"})
@Html.ValidationMessageFor(model => model.Dept_Id, null, new { style="color:red;"})
</div>
<p>
<input type="submit" value="Create" />
</p>
控制器:
[HttpPost]
public ActionResult Create(Faculty faculty)
{
faculty.Email = faculty.F_Name + "." + faculty.L_Name + "@mitcoe.edu.in";
if (ModelState.IsValid)
{
db.Faculty.Add(faculty);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.Dept_Id = new SelectList(db.Department, "Id", "Dept_Name", faculty.Dept_Id);
return View(faculty);
}
下拉列表工作正常,所有字段的 ID 都从视图中正确获取。
但是在 post 函数中,modelstate 是无效的,因为它Dept_name
是 null。
ORM 仅Dept_Id
使用外键创建表。
为什么控制器Dept_Name
也在期待?我的模型有什么问题吗?