gregoryp
gregoryp

Reputation: 1019

Model.List is null after post in ASP.NET MVC

I know there's other questions about this, but I want a better explanation about it.

I want to show a table with my Model.List and after POST I still need to access that list. Today this is not happening.

This is my cshtml:

@foreach (var student in Model.ListSchedulingDetails)
    {
        <tr>
            <td width="150">
                @Html.DisplayFor(modelItem => student.SchedulingDate)
            </td>
            <td width="250">
                @Html.DisplayFor(modelItem => student.TeacherName)
            </td>
            <td width="250">
                @Html.DisplayFor(modelItem => student.StudentName)
            </td>
            <td width="150">
                @Html.DisplayFor(modelItem => student.SchedulingHour)
            </td>
            <td width="250">
                @Html.DisplayFor(modelItem => student.SchedulingObservation)
            </td>
        </tr>
    }

After POST, my Model.ListSchedulingDetails is null. What's happening?

Upvotes: 0

Views: 2336

Answers (1)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62498

There are two things here:

  1. DisplayFor() is for only displaying. For posting, we need input elements like HiddenFor(),TextBoxFor()

  2. you would need to index them for posting back in case of collections, foreach wouldn't help

Your code would need to be like:

 @for (int i=0; i< Model.ListSchedulingDetails.Count; i++)
 {
     <tr>
        <td width="150">
            @Html.DisplayFor(modelItem => ListSchedulingDetails[i].SchedulingDate)
            @Html.HiddenFor(modelItem => ListSchedulingDetails[i].SchedulingDate)
        </td>
        <td width="250">
            @Html.DisplayFor(modelItem => ListSchedulingDetails[i].TeacherName)
            @Html.HiddenFor(modelItem => ListSchedulingDetails[i].SchedulingDate)
        </td>
        <td width="250">
            @Html.DisplayFor(modelItem => ListSchedulingDetails[i].StudentName)
           @Html.HiddenFor(modelItem => ListSchedulingDetails[i].SchedulingDate)
        </td>
        <td width="150">
           @Html.DisplayFor(modelItem => ListSchedulingDetails[i].SchedulingHour)
           @Html.HiddenFor(modelItem => ListSchedulingDetails[i].SchedulingDate)
        </td>
        <td width="250">
            @Html.DisplayFor(modelItem => ListSchedulingDetails[i].SchedulingObservation)
            @Html.HiddenFor(modelItem => ListSchedulingDetails[i].SchedulingDate)
        </td>
    </tr>
 }

Upvotes: 7

Related Questions