How to display database records in asp.net mvc view

doncadavona picture doncadavona · Aug 13, 2014 · Viewed 95.9k times · Source

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 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.

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>

Answer

Giannis Paraskevopoulos picture Giannis Paraskevopoulos · Aug 13, 2014

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>