C# 在foreach循环中尝试使用if语句时,“对象引用未设置为对象的实例”
我有一张表格,上面显示了学生每修一门课的情况。我有一个foreach循环,遍历学生的所有注册C# 在foreach循环中尝试使用if语句时,“对象引用未设置为对象的实例”,c#,asp.net,asp.net-mvc,razor,foreach,C#,Asp.net,Asp.net Mvc,Razor,Foreach,我有一张表格,上面显示了学生每修一门课的情况。我有一个foreach循环,遍历学生的所有注册 @foreach (var item in Model.Enrollments) { <tr> <td> @Html.DisplayFor(modelItem => item.Course.CourseID) </td> <td> @Html.DisplayFor(modelItem => item.Co
@foreach (var item in Model.Enrollments)
{
<tr>
<td> @Html.DisplayFor(modelItem => item.Course.CourseID) </td>
<td> @Html.DisplayFor(modelItem => item.Course.Title) </td>
<td> @Html.DisplayFor(modelItem => item.Course.Type) </td>
<td> @Html.DisplayFor(modelItem => item.Status) </td>
</tr>
}
正如代码编写者所指出的,您已经得到了一个item对象,其中包含一个设置为null的Course对象 由于item对象不为null,因此它是从枚举中提取的。然后,在检查内部课程对象时,它会抛出异常,因为它为null。为了避免在计算对象之前只检查null,如下所示:
@foreach (var item in Model.Enrollments)
{
if (item.Course != null && item.Course.Type == "Basic Core")
{
<tr>
<td> @Html.DisplayFor(modelItem => item.Course.CourseID) </td>
<td> @Html.DisplayFor(modelItem => item.Course.Title) </td>
<td> @Html.DisplayFor(modelItem => item.Course.Type) </td>
<td> @Html.DisplayFor(modelItem => item.Status) </td>
</tr>
}
}
如果需要,您还可以调试razor代码以查看发生了什么。您的内部课程对象为空,这就是错误的原因。如果您的评论解决了问题,并完美地说明了解决方案。谢谢,很高兴它帮助了您Niko。
Line 113:{
Line 114:
Line 115: if (item.Course.Type == "Basic Core") {
Line 116: <tr>
Line 117: <td> @Html.DisplayFor(modelItem => item.Course.CourseID) </td>
public ActionResult Details(int? StudentID)
{
if (StudentID == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Student student = db.Students.Find(StudentID);
if (student == null)
{
return HttpNotFound();
}
return View(student);
}
@foreach (var item in Model.Enrollments)
{
if (item.Course != null && item.Course.Type == "Basic Core")
{
<tr>
<td> @Html.DisplayFor(modelItem => item.Course.CourseID) </td>
<td> @Html.DisplayFor(modelItem => item.Course.Title) </td>
<td> @Html.DisplayFor(modelItem => item.Course.Type) </td>
<td> @Html.DisplayFor(modelItem => item.Status) </td>
</tr>
}
}