C# 代码首次提交模型列表的空引用
当我使用CF EF提交到数据库时,我在页面模型的模型列表中得到一个空引用异常,这里:C# 代码首次提交模型列表的空引用,c#,asp.net-mvc,entity-framework,C#,Asp.net Mvc,Entity Framework,当我使用CF EF提交到数据库时,我在页面模型的模型列表中得到一个空引用异常,这里:db.colleges.SaveChanges(college)。页面上的模型是college,每个college都有一个学生的列表。当我在ActionResult上添加一个断点并将鼠标悬停在解析的in college值上时,它在students属性上显示null,而我希望计数为1(或无论我添加了多少) 我错过了什么 代码 控制器内的违规行为方法 private CollegeContext db = new C
db.colleges.SaveChanges(college)代码>。页面上的模型是college
,每个college
都有一个学生的列表。当我在ActionResult上添加一个断点并将鼠标悬停在解析的in college值上时,它在students属性上显示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.College
@{
ViewBag.Title=“创建”;
}
创造
@使用(Html.BeginForm())
{
@Html.AntiForgeryToken()
学院
@Html.ValidationSummary(true,“,new{@class=“text danger”})
@LabelFor(model=>model.name,htmlAttributes:new{@class=“controllabel col-md-2”})
@EditorFor(model=>model.name,new{htmlAttributes=new{@class=“form control”})
@Html.ValidationMessageFor(model=>model.name,“,new{@class=“text danger”})
@foreach(Model.students中的var项)
{
@Html.Partial(“StudentView”,项目)
}
@ActionLink(“Add”,“StudentManager”,null,新的{id=“addItemStudents”,@class=“btn btn default”})
}
@ActionLink(“返回列表”、“索引”)
@节脚本{
@Scripts.Render(“~/bundles/jqueryval”)
$(函数(){
$('#addItemStudents')。在('click',函数(){
$.ajax({
url:“@url.Action”(“StudentManager”),
cache:false,
成功:函数(html){$(“#editorRowsStudents”).append(html)}
});
返回false;
});
$('#editorRowsStudents')。在('click','.deleteRow',函数(){
$(this).closest('.editorRow').remove();
});
});
}
学生部分
@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>
@model Register.Models.Student
@使用(Html.BeginCollectionItem(“学生”))
{
@Html.TextBoxFor(m=>m.firstName)
@Html.TextBoxFor(m=>m.lastName)
}
模型
[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; }
}
[表格(“学院”)]
公立学院
{
[关键]
public int collegeId{get;set;}
[显示名称(“名称”)]
公共字符串名称{get;set;}
//导航属性以跟踪属于学院的学生
公共虚拟IList学生{get;set;}
}
[表(“学生”)]
公立班学生
{
[关键]
公共int studentId{get;set;}
public int collegeId{get;set;}
[ForeignKey(“collegeId”)]
//导航属性以跟踪该学生所属的大学
公立大学学院{get;set;}
[显示名称(“名字”)]
公共字符串名{get;set;}
[显示名称(“姓氏”)]
公共字符串lastName{get;set;}
}
您的[Bind(include=“…”)
属性将属性学生从绑定中排除。删除它(如果您发现自己正在使用它,请不要使用视图模型)看起来变量或属性为null。设置断点并逐步遍历代码以查找空变量/属性。您还可以发布整个异常消息,该消息可能会告诉您哪个属性为null,但这不会改变您调试代码所需的事实。student的students属性列表返回null,但它们是使用控制器中的StudentManager在partial through BeginCollectionItem中创建的。