18

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>
4
  • 2
    It won't work - the design is bad - you cannot fetch data from SqlDataReader after connection disposal (using clausule). Have you read some MVC / Razor tutorials? Commented Aug 13, 2014 at 6:38
  • 2
    Yes, I know its bad structure. Thats why I need to know from you experienced guys to share what you know is the best way. :) I just started with ASP.NET MVC with C# Commented Aug 19, 2014 at 8:52
  • Thank you Giannis! from (stackoverflow.com/users/2401981/giannis-paraskevopoulos) Your answer works and I believe its the best way to solve my case. Commented Aug 19, 2014 at 8:55
  • 1
    I also found this link from DotFunda.com which solves my case and is same solution as Gianinis said: dotfunda.com/articles/show/2550/… Commented Aug 19, 2014 at 8:56

2 Answers 2

61

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>
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you ver much this really helped. I even learned how to use Models with this!
I am very glad this was a help to you. You may as well accept it as an answer for future readers, and if you wish also upvote.
O yes sure. I still can't up vote now. But I'll do when I have enough reputation here at SOF. Thanks!
5

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.