0

在带有 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 模型的创建视图中添加一个组合框,让我从数据库中的学校列表中选择一所学校

谢谢!

4

1 回答 1

0

在您的 (get) create 方法中,您需要添加一个方法来提供 Schools 数据:

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);
}
于 2012-07-18T07:59:46.893 回答