ASP.NET Core MVC 控制查询数据表后在视图显示
如果是手动写代码,不用VS自带的一些控件,那比较简单的方式就是把查询的数据集,逐条赋给对象模型,再加到List,最后在控制加到 ViewBag,视图循环显示ViewBag变量
控制器代码
List<Users> list = new List<Users>();
using (MySqlConnection conn = new MySqlConnection(DbConfig.Mysqlcon))
{
string sqls = "SELECT * FROM Users";
MySqlCommand cmd = new MySqlCommand(sqls, conn);
conn.Open();
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Users u1 = new Users();
u1.UName = reader.GetString(1);
......
list.Add(u1);
}
}
ViewBag.Users = list;
return View();
视图代码
@foreach (var item in ViewBag.Users)
{
<tr>
<td>@item.UName</td>
......
</tr>
}