1

嗨,我正在一个MVC 3应用程序中工作。我有一个带有以下代码的创建表单。

@model Xrm.Student
@{
ViewBag.Title = "Create Student Record";
 }
@using (Html.BeginForm("Create", "Student", FormMethod.Post))
{
    <div class="editor-label">
         @Html.LabelFor(model => @Model.FirstName)
    </div>
    <div class="editor-field">                                      
         @Html.EditorFor(model => @Model.FirstName)
         @Html.ValidationMessageFor(model => @Model.FirstName)
    </div>
<div>
    <input id="Submit1" type="submit" value="Submit" />
</div>
}

我想在 Firsname 字段下添加一个新的下拉列表,该下拉列表应该填充 pubjects。主题是不同的实体。我可能很容易,但我是 MVC 的新手,所以我就卡在这里了。谁能建议我实现它的方法。

谢谢并恭祝安康

4

1 回答 1

4

我会定义一个视图模型:

public class MyViewModel
{
    public Student Student { get; set; }

    [DisplayName("Subject")]
    [Required]
    public string SubjectId { get; set; }

    public IEnumerable<Subject> Subjects { get; set; }
}

然后让您的控制器填充并将此视图模型传递给视图:

public ActionResult Create()
{
    var model = new MyViewModel();
    model.Student = new Student();
    model.Subjects = db.Subjects;
    return View(model);
}

最后将您的视图强类型化到视图模型中:

@model MyViewModel
@{
    ViewBag.Title = "Create Student Record";
}
@using (Html.BeginForm())
{
    <div class="editor-label">
         @Html.LabelFor(x => x.Student.FirstName)
    </div>
    <div class="editor-field">                                      
         @Html.EditorFor(x => x.Student.FirstName)
         @Html.ValidationMessageFor(x => x.Student.FirstName)
    </div>

    <div class="editor-label">
         @Html.LabelFor(x => x.SubjectId)
    </div>
    <div class="editor-field">                                      
         @Html.DropDownListFor(
             x => x.SubjectId, 
             new SelectList(Model.Subjects, "Id", "Name"),
             "-- Subject --"
         )
         @Html.ValidationMessageFor(x => x.SubjectId)
    </div>

    <div>
        <input type="submit" value="Submit" />
    </div>
}

我用于 SelectList的"Id"和值显然必须是您想要用作分别绑定下拉列表中每个选项的 id 和文本的类上的现有属性。"Name"Subject

于 2012-04-17T14:37:27.453 回答