0

我在 MVC3 视图中添加了 IF 条件,但它不起作用:

@model IEnumerable<StudentRegistrationPortal.Models.CourseRegisterModel>   
@{
    ViewBag.Title = "Welcome Student";
}

<h2>Welcome 
@Context.User.Identity.Name
</h2>
@Html.ActionLink("[Sign Out]", "SignOut", "Student")
<ul>
    <li>@Html.ActionLink("Register Courses", "registerCourses", "Course")</li>
</ul>

<h3>Pending Courses</h3>
<table border="1">
<tr>
    <th>RollNumber
    </th>
    <th>Course Code
    </th>
    <th>Course Name
    </th>
    <th>Status</th>
</tr>

@foreach (StudentRegistrationPortal.Models.CourseRegisterModel modelValue in Model)
{
    if (!string.IsNullOrEmpty(modelValue.Course.Code))
    {
    <tr>
        <td>
            @Context.User.Identity.Name
        </td>
        <td>
            @Html.DisplayFor(modelItem => modelValue.Course.Code)
        </td>
        <td>
            @Html.DisplayFor(modelItem => modelValue.Course.Name)
        </td>
        <td>Pending
        </td>
    </tr>
    }
}

</table>

执行 IF 语句时出现以下错误: Object reference not set to an instance of an object.

IF 条件的目的是确认该modelValue.Course.Code值不是空字符串或空值。

4

1 回答 1

5

Course本身很可能是空的。您需要检查两者:

if (modelValue.Course!=null &&   !string.IsNullOrEmpty(modelValue.Course.Code))
 {
 //etc
 }
于 2013-08-01T18:21:11.517 回答