C# MVC3视图中的IF条件

C# MVC3视图中的IF条件,c#,asp.net-mvc-3,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

我在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>
@model IEnumerable
@{
ViewBag.Title=“欢迎学生”;
}
欢迎
@Context.User.Identity.Name
@ActionLink(“[注销],“注销”,“学生”)
  • @ActionLink(“注册课程”、“注册课程”、“课程”)
待修课程 卷数 课程代码 课程名称 地位 @foreach(StudentRegistrationPortal.Models.CourseRegisterModel模型中的模型值) { 如果(!string.IsNullOrEmpty(modelValue.Course.Code)) { @Context.User.Identity.Name @DisplayFor(modelItem=>modelValue.Course.Code) @DisplayFor(modelItem=>modelValue.Course.Name) 悬而未决的 } }
在执行IF语句时,会出现以下错误:
对象引用未设置为对象的实例。


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

很可能
Course
本身是null。您需要检查以下两项:

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

课程
本身很可能为空。您需要检查以下两项:

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