将ASP.NET MVC与C#一起使用,如何将一些数据库记录传递给View并以表格形式显示?
我需要知道如何从已经返回到SqlDataReader对象的数据库传输/传递一些记录行并将该对象传递给View,这样我就可以在View中显示该对象包含的所有记录的foreach。
以下代码就是我正在尝试做的事情。但它不起作用。
控制器:
public ActionResult Students()
{
String connectionString = "<THE CONNECTION STRING HERE>";
String sql = "SELECT * FROM students";
SqlCommand cmd = new SqlCommand(sql, connectionString);
using(SqlConnection connectionString = new SqlConnection(connectionString))
{
connectionString.Open();
SqlDataReader rdr = cmd.ExecuteReader();
}
ViewData.Add("students", rdr);
return View();
}
观点:
<h1>Student</h1>
<table>
<!-- How do I display the records here? -->
</table>
答案 0 :(得分:45)
<强> 1。首先创建一个Model
来保存记录的值。例如:
public class Student
{
public string FirstName {get;set;}
public string LastName {get;set;}
public string Class {get;set;}
....
}
<强> 2。然后将阅读器中的行加载到列表或其他内容中:
public ActionResult Students()
{
String connectionString = "<THE CONNECTION STRING HERE>";
String sql = "SELECT * FROM students";
SqlCommand cmd = new SqlCommand(sql, conn);
var model = new List<Student>();
using(SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while(rdr.Read())
{
var student = new Student();
student.FirstName = rdr["FirstName"];
student.LastName = rdr["LastName"];
student.Class = rdr["Class"];
....
model.Add(student);
}
}
return View(model);
}
第3。最后在您的View
中,声明您的模型类型:
@model List<Student>
<h1>Student</h1>
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Class</th>
</tr>
@foreach(var student in Model)
{
<tr>
<td>@student.FirstName</td>
<td>@student.LastName</td>
<td>@student.Class</td>
</tr>
}
</table>
答案 1 :(得分:4)
如果您不必使用SQL阅读器,那么让控制器更容易这样。
<强> Controller.cs 强>
private ConnectContext db = new ConnectContext();
public ActionResult Index()
{
return View(db.Tv.ToList());
}
<强> ConnectContext.cs 强>
public class ConnectContext : DbContext
{
public DbSet<Student> Student{ get; set; }
}
这样您的连接字符串将在您的web.config中,View + Model将保持不变。