简体   繁体   English

在ASP.NET MVC中发布后,Model.List为null

[英]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. 我想显示一个带有Model.List的表,并且在POST之后,我仍然需要访问该列表。 Today this is not happening. 今天,这没有发生。

This is my cshtml: 这是我的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. POST之后,我的Model.ListSchedulingDetails为空。 What's happening? 发生了什么?

There are two things here: 这里有两件事:

  1. DisplayFor() is for only displaying. DisplayFor()仅用于显示。 For posting, we need input elements like HiddenFor() , TextBoxFor() 对于发布,我们需要输入元素,例如HiddenFor()TextBoxFor()

  2. you would need to index them for posting back in case of collections, foreach wouldn't help 您需要将它们编入索引以便在出现收藏集的情况下发回, foreach并没有帮助

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>
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM