如何解决.Net Core中的NullReferenceException错误

时间:2019-08-05 20:59:59

标签: .net nullreferenceexception core

.net核心和MVC的新手。花一整天试图弄清楚为什么我收到NullReferenceException错误。我正在调用的存储过程只是报告ID的简单选择。

我已经查看了许多答案,是的,我可以在View中检查是否为空,但是我正在调用的存储过程确实有结果并且应该返回数据,但是页面页面上显示NullReferenceException。我的连接字符串,模型,控制器和视图都完全像另一个可以正常工作的页面。

DataAccessLayer:

public class DWReportsDataAccessLayer
{

    string connectionString = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=myTestDB;Data Source=mySQLEXPRESS";

    public IEnumerable<Reports> GetAllReports()
    {
        List<Reports> lstreport = new List<Reports>();

        using (SqlConnection con = new SqlConnection(connectionString))
        {
            SqlCommand cmd = new SqlCommand("GetAllReportListTEST", con);
            cmd.CommandType = CommandType.StoredProcedure;

            con.Open();
            SqlDataReader rdr = cmd.ExecuteReader();

            while (rdr.Read())
            {
                Reports report = new Reports();

                report.ReportID = Convert.ToInt32(rdr["ReportID"]);


                lstreport.Add(report);
            }
            con.Close();

        }
        return lstreport;
    }


}

型号:

public class Reports
{
    public int ReportID { get; set; }


}

控制器:

public class ReportsController : Controller
{

    DWReportsDataAccessLayer objreport = new DWReportsDataAccessLayer();
    public IActionResult Index()
    {
        List<Reports> lstReport = new List<Reports>();
        lstReport = objreport.GetAllReports().ToList();
        return View();
    }
}

查看:

<table class="display" id="ReportTbl">
<thead>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.ReportID)
        </th>
   </tr>
</thead>
<tbody>
     @foreach (var item in Model)
        {
             <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.ReportID)
                    </td>
             </tr>
       }
 </tbody>

这是我的错误-但正如我提到的,此记录集不应为空,所以我不明白为什么会出错:

NullReferenceException:对象引用未设置为应该在其上呈现结果的该行对象的实例……@foreach(模型中的var项)

0 个答案:

没有答案