【问题标题】:Binding ICollection to edit form in MVC asp .NET绑定 ICollection 以在 MVC asp .NET 中编辑表单
【发布时间】:2015-07-22 11:42:27
【问题描述】:

我有两个模型:StudentCourse。我想创建一个简单的表单来编辑课程信息,例如课程名称,以及在课程中添加或删除学生。为此,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。但是您不能将列表框绑定到复杂对象的集合。您的模型需要一个属性(例如) public int[] SelectedStudents { get; set; } 假设您的选项的值是int

标签: asp.net asp.net-mvc


【解决方案1】:

您需要在Course 模型中创建一个List&lt;int&gt;。所以,它可以映射到它。从列表框中选择的值将返回 List&lt;int&gt; 而不是 List&lt;Student&gt;。因此,如果您无法编辑现有模型,则需要为此创建一个ViewModel

以下是示例课程模型或视图模型。

public class Course
    {
        public int Id { get; set; }
        public string CourseName { get; set; }
        public string Time { get; set; }
        public List<int> Students { get; set; }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-25
    相关资源
    最近更新 更多