【发布时间】:2019-06-17 17:28:49
【问题描述】:
我尝试加入两个表,但出现无法对空引用执行运行时绑定如何解决此问题。
代码:- 控制器:
public ActionResult Index()
{
string query = "SELECT* FROM Student AS A INNER JOIN Demo AS B ON A.S_ID = B.S_ID ";
List<Result> result = new List<Result>();
using (SqlConnection connection = new SqlConnection(connectionstring))
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Connection = connection;
connection.Open();
using (SqlDataReader sdr = command.ExecuteReader())
{
while (sdr.Read())
{
result.Add(new Result
{
S_Name = sdr["S_Name"].ToString(),
S_LName = sdr["S_LName"].ToString(),
Status = sdr["Status"].ToString()
});
}
}
connection.Close();
}
return View();
}
索引:
<table class="table table-condensed table-hover">
<thead>
<tr>
<td>S_Name</td>
<td>S_LName</td>
<td>Status</td>
</tr>
</thead>
<tbody>
@foreach (var per in Model.Result)
{
<tr>
<td>@per.S_Name</td>
<td>@per.S_LName</td>
<td>@per.Status</td>
</tr>
}
</tbody>
</table>
结果模型是两个表的连接模型,如何修改上面的代码
【问题讨论】:
-
您没有将任何模型数据发送到您的视图,因此整个模型为空。你的意思是
return View(result);吗? -
然后你需要
foreach (var per in Model) {,因为模型将是一个列表,它不会有一个名为 Result 的属性。但所有这些都是假设,我不知道您在视图代码中将模型设置为什么类型。 -
我修改了返回视图(结果),但在视图方面它只显示列名它不显示任何记录
-
非常感谢您的回复,我解决了上述问题。
标签: asp.net-mvc