Code First提交模型列表的空引用

时间:2015-08-27 13:20:57

标签: c# asp.net-mvc entity-framework

当我使用CF EF提交数据库时,我在页面模型中的模型列表中获得了空引用异常,此处为:db.colleges.SaveChanges(college);。页面上的模型为college,每个college都有student列表。当我在ActionResult上添加一个断点并将鼠标悬停在大学解析的值上时,它会在学生属性上显示null,当我期望计数为1时(或者我添加了多少)。

我错过了什么?

代码

控制器内的违规行为方法

private CollegeContext db = new CollegeContext();
public ActionResult StudentManager()
        {
            return PartialView("StudentView", new Student());
        }
 [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "collegeId,name")] College college)
        {
            if (ModelState.IsValid)
            {
                db.colleges.Add(college);

                foreach(var s in college.students)
                {
                    var stu = new Student()
                    {
                       firstName = s.firstName,
                       lastName = s.lastName
                    };
                    db.students.Add(stu);
                }

                db.SaveChanges();

                return RedirectToAction("Index");
            }

            return View(college);
        }

创建页面

@model Register.Models.College

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>


@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>College</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.name, "", new { @class = "text-danger" })
            </div>
        </div>
        <div id="editorRowsStudents">
            @foreach (var item in Model.students)
            {
                @Html.Partial("StudentView", item)
            }
        </div>
        @Html.ActionLink("Add", "StudentManager", null, new { id = "addItemStudents", @class="btn btn-default" })

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
    $(function () {
        $('#addItemStudents').on('click', function () {
            $.ajax({
                url: '@Url.Action("StudentManager")',
                    cache: false,
                    success: function (html) { $("#editorRowsStudents").append(html); }
                });
                return false;
            });
            $('#editorRowsStudents').on('click', '.deleteRow', function () {
                $(this).closest('.editorRow').remove();
            });
        });
</script>
}

学生部分

@model Register.Models.Student

<div class="editorRow">
    @using (Html.BeginCollectionItem("students"))
    {
        <div class="ui-grid-c ui-responsive">
            <div class="ui-block-a">
                <span>
                    @Html.TextBoxFor(m => m.firstName)
                </span>
            </div>
            <div class="ui-block-b">
                <span>
                    @Html.TextBoxFor(m => m.lastName)
                </span>
            </div>
            <div class="ui-block-c">
                <span>
                    <span class="dltBtn">
                        <a href="#" class="deleteRow">X</a>
                    </span>
                </span>
            </div>
        </div>
    }
</div>

模型

[Table("College")]
    public class College
    {
        [Key]
        public int collegeId { get; set; }
        [DisplayName("Name")]
        public string name { get; set; }
        // navigation property to keep track of the student(s) that belong to the college
        public virtual IList<Student> students { get; set; }
    }

    [Table("Student")]
    public class Student
    {
        [Key]
        public int studentId { get; set; }
        public int collegeId { get; set; }
        [ForeignKey("collegeId")]
        // navigation property to keep track of which college the student belongs
        public College college { get; set; }
        [DisplayName("First Name")]
        public string firstName { get; set; }
        [DisplayName("Last Name")]
        public string lastName { get; set; }
    }

1 个答案:

答案 0 :(得分:2)

您的[Bind(include = "...")]属性会将属性students排除在绑定之外。删除它(如果您发现自己使用它,请不要使用视图模型)

相关问题