How to display database records in asp.net mvc view

前端 未结 2 598
旧巷少年郎
旧巷少年郎 2020-12-07 23:12

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 record

2条回答
  •  囚心锁ツ
    2020-12-07 23:59

    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 = "";
        String sql = "SELECT * FROM students";
        SqlCommand cmd = new SqlCommand(sql, conn);
    
        var model = new List();
        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

    @foreach(var student in Model) { }
    First Name Last Name Class
    @student.FirstName @student.LastName @student.Class

提交回复
热议问题