1

Building a dynamic list in MVC5. Form will post to the controller and I can see the StudentList correctly populated in chrome dev tools but in the controller, the StudentList is empty.

Model:

public class Student
{
    public int id { get; set; }
    public string Name { get; set; }
}

public class StudentViewModel
{
    public Student student { get; set; }
    public List<Student> StudentList { get; set; }
}

View:

@model TaskTrack.ViewModels.StudentViewModel

    @using (Html.BeginForm("Create", "Timesheet", FormMethod.Post, new { @id = "addTaskForm" }))
    {
        <div id="task-row">
           //Partial view renders here.
        </div>
        <button class="btn save-day" type="submit" >Save Day</button>
    }

Partial view:

@model TaskTracker.ViewModels.StudentViewModel

@using (Html.BeginCollectionItem("StudentList"))
{
    <div class="form-row">
        <div class="form-group col-2">
            @Html.EditorFor(model => model.Student.Name, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Student.Name, "", new { @class = "text-danger" })
        </div>
    </div>
}

If I take out the Student instance from the ViewModel and replace it with the student model properties, then change the partial view to bind directly to the Name property, it will work.

@Html.EditorFor(model => model.Student.Name, new { htmlAttributes = new { @class = "form-control" } })

to

@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })

Controller post:

    [HttpPost]
    public ActionResult Create(StudentViewModel model)

When I intercept the post before it hits the controller, I can see it has bound correctly, but in the controller StudentList is empty.

I am trying to avoid having the student model duplicated in the view model because it's duplicate and all the validation rules are already in the Student model, so I would have to duplicate all that in the viewmodel as well, which seems wrong.

BattlFrog
  • 3,370
  • 8
  • 56
  • 86
  • Your `StudentViewModel` is strange, why do you have `Student` and `StudentList` in the same ViewModel? I also don't see you using `StudentList` anywhere in your form, are you expecting it to get populated? – Hooman Bahreini May 09 '19 at 02:02
  • @HoomanBahreini - Student is a single student, StudentList is a list of Student and it is what the collection binds to in the partial view. – BattlFrog May 09 '19 at 14:27

0 Answers0