I have tried to pass a list of objects in a model from view to controller via ajax It returns blank list and throw this error
$exception {" Object reference not set to an instance of an object."} System.NullReferenceException Model muproject.ViewModel.StudentsVM .Students.get returned null.
Controller
[HttpPost]
public ActionResult AddStudents(StudentsVM students) {
return new JsonResult
{
// students.Students.Count this line causes the excption
Data = "Successfull " + students.Students.Count
};
}
Model
public class StudentsVM
{
public List<Student> Students { get; set; }
//other fields
}
Student is model in Models
View
@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);
}
});
});
and javascript code to add and delete students