Tuesday, 30 August 2016

How to display database records in asp.net mvc view

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);

    using(SqlConnection conn = new SqlConnection(connectionString))
    {
        conn.Open();
        SqlDataReader rdr = cmd.ExecuteReader();
        var model = new List<Student>();
        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>

No comments:

Post a Comment