MVC3视图中的IF条件

时间:2013-08-01 18:19:18

标签: c# asp.net-mvc-3

我在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值不是空字符串或null。

1 个答案:

答案 0 :(得分:5)

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

if (modelValue.Course!=null &&   !string.IsNullOrEmpty(modelValue.Course.Code))
 {
 //etc
 }