在我的asp.net core项目中,某部分视图为:
<table>
<thead>
<tr>
<th>MultimediaName</th>
<th>MultimediaBelongsName</th>
<th>MultimediaNotary</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>@Html.DisplayFor(modelItem => item.MultimediaName)</td>
<td>@Html.DisplayFor(modelItem => item.MultimediaBelongsName)</td>
<td>@Html.DisplayFor(modelItem => item.MultimediaNotary)</td>
</tr>
}
</tbody>
</table>
对应的控制器代码为:
public IActionResult Search([FromForm]string word)
{
string LoginConnection = "(数据库连接字符串)";
SqlConnection conn = new SqlConnection(LoginConnection);
conn.Open();
string sql = "select * from Multimedium where MultimediaName='" + word (视图文本框内容)+ "'";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader sqldr = cmd.ExecuteReader();
if (sqldr.Read())
{}
return View();
}
编译没有问题,运行时出现了 System.NullReferenceException: Object reference not set to an instance of an object.然后指向的是视图的这行代码:@foreach (var item in Model)。请问下这是什么原因导致的错误呢?
报错是哪一段代码
应该是 Model 为空,因为你在controller里面虽然根据查找条件查询出了符合条件的数据库记录。但是你没有把这些数据返回给前端页面。不过在此之前,你应该需要把sqlDataReader 转换为List 然后随页面返回。
举个现成的例子:
List<Student> resultList= new List<Student>();
while (reader.Read())
{
Student entity= new Student();
entity.ID = (int)reader["ID"];
entity.Name= (string)reader["Name"];
// ...
//
resultList.Add(entity);
}
return view(resultList)