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
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 = "";
String sql = "SELECT * FROM students";
SqlCommand cmd = new SqlCommand(sql, conn);
var model = new List();
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
First Name
Last Name
Class
@foreach(var student in Model)
{
@student.FirstName
@student.LastName
@student.Class
}