您好我正在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的新手,所以我只是坚持到这里。任何人都可以建议我实现它的方法。
谢谢和问候
答案 0 :(得分: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"
和"Name"
值显然必须是Subject
类上的现有属性,您希望将它们用作分别绑定每个的id和文本下拉选项。