ASP.NET MVC > Entity Framework

Listing records in Grid in ASP.NET MVC

How to quickly list records in Grid in ASP.NET MVC?

To list database records in the Grid in ASP.NET MVC, we can follow below approach in which we shall use System.Web.UI.WebControls namespace.


public ActionResult ListDataInGridView()
                  System.Web.UI.WebControls.GridView gView = new
            gView.DataSource = db.PersonalDetails.ToList();
            using (System.IO.StringWriter sw = new System.IO.StringWriter())
                      using (System.Web.UI.HtmlTextWriter htw = new
                    ViewBag.GridViewString = sw.ToString();
            return View();

In the above code snippet, we are instantiating the GridView control class and setting the DataSource to the list of records from the database and calling the DataBind() method of the GridView. This GridView is the same control as we used in the ASP.NET Web Forms to list the data.

After setting the DataSource and calling the DataBind() method, we are using StringWriter and HtmlTextWriter into which the content of the GridView is rendered. Then the same is being set as the ViewBag.GridViewString.


    ViewBag.Title = "ListDataInGridView";

<h2>List Data In GridView</h2>


In the view, we are simply using @Html.Raw method to write the GridView content set into ViewBag in the Action method. If we do not use @Html.Raw method, the output will be the HTML encoded characters so it will instead of bringing records into tabular format in the browser will simply writes the html table, rows and columns source code as output on the browser.


Note that all the properties of the PersonalDetail class has been converted as heading and records have been converted into the rows of the GridView. This is the best way to quicly list records from the DataSource into ASP.NET MVC.

 Views: 1862 | Post Order: 109

Write for us