【问题标题】:How to handle NullReferenceException in a foreach loop?如何在 foreach 循环中处理 NullReferenceException?
【发布时间】:2020-08-26 21:08:06
【问题描述】:

我总是收到此错误代码。我知道问题出在哪里,但我不知道为什么。我猜我的模型是 NULL 但在我看来,它不为空。 错误代码:

处理请求时发生未处理的异常。 NullReferenceException: 对象引用未设置为对象的实例。

这里出了点问题:@foreach(var emp in Model)

我的观点:

@model IEnumerable<CRUDDemo.Models.EmployeeInfo>
@{
    ViewData["Title"] = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h1>Index</h1>

<p>
    <a asp-action="Create">Create New</a>
</p>

@*For Display Employee Info*@
<table class="table table-striped">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Name)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Gender)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Company)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Department)
            </th>
        </tr>
    </thead>
    <tbody>
        @foreach(var emp in Model)
        {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => emp.Name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => emp.Gender)
            </td>
            <td>
                @Html.DisplayFor(modelItem => emp.Company)
            </td>
            <td>
                @Html.DisplayFor(modelItem => emp.Department)
            </td>
            <td>
                <a asp-action="Edit" asp-route-id="@emp.ID">Edit</a>
                <a asp-action="Details" asp-route-id="@emp.ID">Details</a>
                <a asp-action="Delete" asp-route-id="@emp.ID">Delete</a>
            </td>
        </tr>
        }
    </tbody>
</table>

我的模特:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;

namespace CRUDDemo.Models
{
    public class EmployeeDAL
    {
        string connectionString = "Data Source=LENOVOL470\\SQLEXPRESS;Initial Catalog=EMPLOYEEDB;Persist Security Info=False;User ID=sa;password=123;";

        //Get All
        public IEnumerable<EmployeeInfo> GetAllEmployee()
        {
            List<EmployeeInfo> empList = new List<EmployeeInfo>();

            using (SqlConnection con = new SqlConnection(connectionString))
            {
                SqlCommand cmd = new SqlCommand("SP_GetAllEmployee", con);
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                con.Open();
                SqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    EmployeeInfo emp = new EmployeeInfo();
                    emp.ID = Convert.ToInt32(dr["ID"].ToString());
                    emp.Name = dr["Name"].ToString();
                    emp.Gender = dr["Gender"].ToString();
                    emp.Company = dr["Company"].ToString();
                    emp.Department = dr["Department"].ToString();

                    empList.Add(emp);
                }
                con.Close();
            }
            return empList;
        }

        //To Insert Employee
        public void AddEmployee(EmployeeInfo emp)
        {
            using (SqlConnection con = new SqlConnection(connectionString))
            {
                SqlCommand cmd = new SqlCommand("SP_InsertEmployee", con);
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.AddWithValue("@Name", emp.Name);
                cmd.Parameters.AddWithValue("@Gender", emp.Gender);
                cmd.Parameters.AddWithValue("@Company", emp.Company);
                cmd.Parameters.AddWithValue("@Department", emp.Department);

                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }

        //To Update Employee
        public void UpdateEmployee(EmployeeInfo emp)
        {
            using (SqlConnection con = new SqlConnection(connectionString))
            {
                SqlCommand cmd = new SqlCommand("SP_UpdateEmployee", con);
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.AddWithValue("@EmpId", emp.ID);
                cmd.Parameters.AddWithValue("@Name", emp.Name);
                cmd.Parameters.AddWithValue("@Gender", emp.Gender);
                cmd.Parameters.AddWithValue("@Company", emp.Company);
                cmd.Parameters.AddWithValue("@Department", emp.Department);

                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }

        //To Delete Employeee
        public void DeleteEmployee(int? empId)
        {
            using (SqlConnection con = new SqlConnection(connectionString))
            {
                SqlCommand cmd = new SqlCommand("SP_DeleteEmployee", con);
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.AddWithValue("@EmpId", empId);

                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }

        //Get Employee by ID
        public EmployeeInfo GetEmployeeById(int? empId)
        {
            EmployeeInfo emp = new EmployeeInfo();

            using (SqlConnection con = new SqlConnection(connectionString))
            {
                SqlCommand cmd = new SqlCommand("SP_GetEmployeeById", con);
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@EmpId", empId);
                con.Open();
                SqlDataReader dr = cmd.ExecuteReader();
                while(dr.Read())
                {
                    emp.ID = Convert.ToInt32(dr["ID"].ToString());
                    emp.Name = dr["Name"].ToString();
                    emp.Gender = dr["Gender"].ToString();
                    emp.Company = dr["Company"].ToString();
                    emp.Department = dr["Department"].ToString();
                }
                con.Close();
            }
            return emp;
        }
    }
}

我的控制器:

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AspNetCore;
using CRUDDemo.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ActionConstraints;

namespace CRUDDemo.Controllers
{
    public class EmployeeController : Controller
    {
        EmployeeDAL employeeDAL = new EmployeeDAL();
        public IActionResult Index()
        {
            List<EmployeeInfo> empList = new List<EmployeeInfo>();
            empList = employeeDAL.GetAllEmployee().ToList();
            return View(empList);
        }

        [HttpGet]
        public IActionResult Create()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Create([Bind] EmployeeInfo objEmp)
        {
            if (ModelState.IsValid)
            {
                employeeDAL.AddEmployee(objEmp);
                return RedirectToAction("Index");
            }
            return View(objEmp);
        }

        public IActionResult Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }
            EmployeeInfo emp = employeeDAL.GetEmployeeById(id);
            if(emp == null)
            {
                return NotFound();
            }
            return View(emp);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Edit(int? id, [Bind] EmployeeInfo objEmp)
        {
            if (id == null)
            {
                return NotFound();
            }
            if (ModelState.IsValid)
            {
                employeeDAL.UpdateEmployee(objEmp);
                return RedirectToAction("Index");
            }
            return View(employeeDAL);
        }
        [HttpGet]
        public IActionResult Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }
            EmployeeInfo emp = employeeDAL.GetEmployeeById(id);
            if (emp == null)
            {
                return NotFound();
            }
            return View(emp);
        }

        public IActionResult Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }
            EmployeeInfo emp = employeeDAL.GetEmployeeById(id);
            if (emp == null)
            {
                return NotFound();
            }
            return View(emp);
        }
        [HttpPost,ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public IActionResult DeleteEmp(int? id)
        {
            employeeDAL.DeleteEmployee(id);
            return RedirectToAction("Index");
        }
    }
}

【问题讨论】:

  • 您能否添加控制器代码,以将正确的模型发送到您发布的视图?我怀疑 Model 在您看来是空的。 (你显示的是 DAL)
  • 当然...我也添加了控制器
  • 我同意,在我看来,您的模型也不应该为空(基于您显示的代码)。然而,显然是这样!因此,在控制器中的 Index 方法中添加一个断点,并在启动视图之前检查 empList 的值。然后在视图中添加断点并检查模型

标签: c# asp.net model-view-controller foreach nullreferenceexception


【解决方案1】:

因为您的 emp 对象为空。快速修复:添加if 条件以检查null 喜欢

    @foreach(var emp in Model)
    {
       @if(emp != null)
       {
            // bind the properties to UI element
       }

【讨论】:

  • 我将这个“if”条件放入我的代码中,但它不能解决我的问题。 (还是谢谢你的回复
【解决方案2】:

您可以将 null 作为模型,也可以将 null 作为数组中的值之一。不过,foreach(var emp in Model?.Where(x =&gt; x != null) ?? Enumerable.Empty&lt;HerePlaceYourClass&gt;) 会正确处理空值

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-09
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-06
    • 1970-01-01
    相关资源
    最近更新 更多