[英]How to display database records in asp.net mvc view
Using ASP.NET MVC with C#, how do you pass some database records to a View and display them in table form? 使用ASP.NET MVC和C#,如何将一些数据库记录传递给View并以表格形式显示它们?
I need to know how I can transfer/pass some rows of records from a database that have been returned to an SqlDataReader object and pass that object to the View so I can display all the records contained by the object in the View using foreach. 我需要知道如何从已返回到SqlDataReader对象的数据库传输/传递一些记录行,并将该对象传递给View,这样我就可以使用foreach显示View中对象所包含的所有记录。
The following code is what I'm I'm trying to do. 以下代码是我正在尝试做的事情。 But its not working. 但它不起作用。
The Controller: 控制者:
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();
}
The View: 风景:
<h1>Student</h1>
<table>
<!-- How do I display the records here? -->
</table>
1. First create a Model
that will hold the values of the record. 1.首先创建一个将保存记录值的Model
。 for instance: 例如:
public class Student
{
public string FirstName {get;set;}
public string LastName {get;set;}
public string Class {get;set;}
....
}
2. Then load the rows from your reader to a list or something: 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. Lastly in your View
, declare the kind of your 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>
If you dont have to use an sql reader would it not be easier to have the Controller like this. 如果您不必使用SQL阅读器,那么让控制器像这样更容易。
Controller.cs Controller.cs
private ConnectContext db = new ConnectContext();
public ActionResult Index()
{
return View(db.Tv.ToList());
}
ConnectContext.cs ConnectContext.cs
public class ConnectContext : DbContext
{
public DbSet<Student> Student{ get; set; }
}
This way your connection string will be in your web.config and the View + Model will remain the same. 这样您的连接字符串将在您的web.config中,View + Model将保持不变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.