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.
CONTROLLER CODE
public ActionResult ListDataInGridView() { System.Web.UI.WebControls.GridView gView = new System.Web.UI.WebControls.GridView(); gView.DataSource = db.PersonalDetails.ToList(); gView.DataBind(); using (System.IO.StringWriter sw = new System.IO.StringWriter()) { using (System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw)) { gView.RenderControl(htw); 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.
LISTDATAINGRIDVIEW.CSHTML VIEW CODE
@{ ViewBag.Title = "ListDataInGridView"; } <h2>List Data In GridView</h2> @Html.Raw(ViewBag.GridViewString)
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.
OUTPUT
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: 11636 | Post Order: 109