通过ajax通过NullReferenceException

时间:2018-04-17 21:01:45

标签: jquery ajax asp.net-mvc

我试图通过ajax将模型中的对象列表从视图传递给控制器​​它返回空白列表并抛出此错误

  

$ exception {“    对象引用未设置为的实例    object。“} System.NullReferenceException模型   muproject.ViewModel.StudentsVM .Students.get返回null。

控制器

[HttpPost]
        public ActionResult AddStudents(StudentsVM students) {

            return new JsonResult
            {
                // students.Students.Count this line causes the excption
                Data = "Successfull " + students.Students.Count
        };

        }

模型

        public class StudentsVM
        {
            public List<Student> Students { get; set; }
        //other fields    
        }

Student is model in Models

查看

    @model myproject.ViewModel.StudentsVM
        <form id="StuForm">              
                 <input type="button" value="+" id="insert" class="btn btn-primary">
                @for (int i= 0;i< Model.Students.Count;i++)
          {
                <input type="hidden" name="Student.Index" value="@i" />
         @Html.EditorFor(model => model.Students[i].studentName, new
        {
            htmlAttributes = new { @Name = "Students[" + j + "].studentName", @class = "form-control required student" }
        })

           @Html.EditorFor(model => model.Students[i].studentId, new
        {
            htmlAttributes = new { @Name = "Students[" + i + "].studentId", @class = "form-control required student" }
        })
        <input type="button" value="-" class="btn btn-danger removeStu" style="margin-left:10px;">
        }
         </form>
       @{
                int j = 0;
            }

的Ajax

       $("#StuForm").submit(function (event) {
            event.preventDefault();

            $.ajax({
                url: '@Url.Action("AddStudents", "Test")',
                type: 'POST',
                cache: false,
                data:$('#StuForm').serialize(),
                success: function (result) {
                 //   $("#response").text(result);
                    alert(result);
                }

            });
        });

和javascript代码添加和删除学生

0 个答案:

没有答案