【发布时间】:2015-07-22 11:42:27
【问题描述】:
我有两个模型:Student 和 Course。我想创建一个简单的表单来编辑课程信息,例如课程名称,以及在课程中添加或删除学生。为此,Course 模型具有属性public virtual ICollection<Student> Students { get; set; }。我创建这样的表单:
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Create Course</h4>
<hr />
@Html.ValidationSummary(true)
@Html.HiddenFor(model => model.Id)
<div class="form-group">
@Html.LabelFor(model => model.CourseName, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.CourseName)
@Html.ValidationMessageFor(model => model.CourseName)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Time, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Time)
@Html.ValidationMessageFor(model => model.Time)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Students, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.ListBoxFor(model => model.Students, (IEnumerable<SelectListItem>)ViewBag.Students)
@Html.ValidationMessageFor(model => model.Students)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
表单将所有学生都提取到列表中,没有任何问题。当我点击保存按钮并开始调试我的应用程序时,课程名称和时间的详细信息已成功传递到服务器,但所选学生没有。不仅如此,当我加载表格时,如果一门课程中有一些学生,这些学生不会在列表中被选中。那么谁能告诉我我犯了什么错误?
【问题讨论】:
-
您不能为
ViewBag属性使用与模型属性相同的名称(两者都是Students) - 将ViewBag属性重命名为(例如)StudentList。但是您不能将列表框绑定到复杂对象的集合。您的模型需要一个属性(例如) publicint[] SelectedStudents { get; set; }假设您的选项的值是int
标签: asp.net asp.net-mvc