Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
124 views
in Technique[技术] by (71.8m points)

c# - How to display database records in asp.net mvc view

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...