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>
If you dont have to use an sql reader would it not be easier to have the Controller like this.
Controller.cs
ConnectContext.cs
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:2. Then load the rows from your reader to a list or something:
3. Lastly in your
View
, declare the kind of your model: