值不能为 null;参数名“Source”

4
 @if ( Model.Select(p=>p.Payments.Any(o=>o.Expires>DateTime.Now))!= null)
 { 

 <table class="table">
     <tr>
         <th>
             @Html.DisplayName("Student ID")
         </th>

         <th>
             @Html.DisplayName("Full Name")
         </th>

         <th>
             @Html.DisplayName("Expiry Date")
         </th>

         <th>
             @Html.DisplayName("Contact Number")
         </th>
         <th></th>


         @foreach (var item in Model.Where(p => p.Payments.Any(o => o.Expires > DateTime.Now)))
         {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.StudentID)

这是MVC项目中的首页,我想显示已过期的学生。我使用了If语句,但不知道为什么会出现异常。

1个回答

2

我已经测试了这段代码,如果模型为空,您确实会收到空异常。

enter image description here

问题在于逻辑流程,您首先进行选择,然后再检查是否为空。

if块中 - 首先检查是否为空,然后再选择结果:

if (Model != null && Model.Select(p => p.Payments.Any(o => o.Expires > DateTime.Now)).Any())

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接