0

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

programmer
  • 109
  • 1
  • 7
  • `$(this)` in `data: $(this).serialize(),` is the ajax function, not you form. And read [this answer](http://stackoverflow.com/questions/30094047/html-table-to-ado-net-datatable/30094943#30094943) to understand how to generate for controls for a collection (do not use a `foreach` loop) –  Apr 17 '18 at 21:48
  • @StephenMuecke I have changed foreach to for and data: $(this).serialize() to (#StuForm).serialize() but same error thrown you can see my updated question please – programmer Apr 17 '18 at 22:11
  • Start by deleting your `new { @Name = "Students[" + j + "].studentName"`etc. Never ever attempt to change the `name` attribute. And the issue is that you need to change the name of the parameter in your POST method o it does not match the name of a property in your model –  Apr 17 '18 at 22:30
  • And your `` is pointless - its not clear what you are doing that for - your models does not contain a collection named `Student` (its `Students` - plural), but that would only be required if you are dynamically deleting items in the view –  Apr 17 '18 at 22:33
  • Start by deleting your new { @Name.. (I have deleted them) And the issue is that you need to change the name of the parameter in your POST method ((o?)) (I did not understand this point) – programmer Apr 17 '18 at 22:39
  • Read the duplicate! Change `StudentsVM students` to `StudentsVM model` (or any name you want except `students` because `Students` is also the name of one of the properties in your model) –  Apr 17 '18 at 22:41
  • now it's not through any exception but newly appended elements not submitted – programmer Apr 17 '18 at 23:26
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/169206/discussion-between-stephen-muecke-and-programmer). –  Apr 17 '18 at 23:57

0 Answers0