在使用EF的ASP.NET MVC 3项目中,我试图弄清楚如何处理复杂的数据类型。
我有一个实体学生和物业学校。当用户创建或编辑实体学生时,我希望用户能够从数据库中的学校列表中选择学校。
我有以下型号:
public class TesterDB : DbContext
{
public DbSet<School> Schools { get; set; }
public DbSet<Student> Students { get; set; }
}
[DataContract]
public class School
{
public int ID { get; set; }
public string Name { get; set; }
}
[DataContract]
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public School School { get; set; }
}
在学生控制器中创建方法:
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Student student)
{
if (ModelState.IsValid)
{
db.Students.Add(student);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(student);
}
学生创建视图:
@model Tester.Models.Student
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Student</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
任何想法如何添加到Studnet模型的创建视图中的组合框,让我从我的数据库中的学校列表中选择一所学校
谢谢!
答案 0 :(得分:0)
在您的(获取)创建方法中,您需要添加一个方法来提供学校数据:
public ActionResult Create()
{
ViewBag.SchoolId = new SelectList(db.Schools, "SchoolId", "Name");
return View();
}
然后在您的视图中,您需要呈现此数据:
<fieldset>
...
<div class="editor-label">
@Html.LabelFor(model => model.SchoolId, "School")
</div>
<div class="editor-field">
@Html.DropDownList("SchoolId", String.Empty)
@Html.ValidationMessageFor(model => model.SchoolId)
</div>
...
</fieldset>
以便在您的帖子中,您可以检索学校ID并将其应用于学生对象:
[HttpPost]
public ActionResult Create(Student student)
{
if (ModelState.IsValid)
{
db.Students.Add(student);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.SchoolId = new SelectList(db.Schools, "SchoolId", "Name", student.SchoolId);
return View(student);
}