Reputation: 2924
I have added IF condition in MVC3 view but its not working:
@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>
It gives following error while executing IF statement:
Object reference not set to an instance of an object.
The purpose of IF condition to confirm that modelValue.Course.Code
value is not empty string or null.
Upvotes: 0
Views: 874
Reputation: 63956
It's very likely that Course
itself is null. You would need to check for both:
if (modelValue.Course!=null && !string.IsNullOrEmpty(modelValue.Course.Code))
{
//etc
}
Upvotes: 5