Using ASP.NET MVC with C#, how do you pass some database records to a View and display them in table form?
I need to know how I can transfer/pass some rows of record
If you dont have to use an sql reader would it not be easier to have the Controller like this.
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; }
}
This way your connection string will be in your web.config and the View + Model will remain the same.
1. First create a Model
that will hold the values of the record. 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:
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:
@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>