In this article, we are going to learn how to quickly list the data from the database into Grid in ASP.NET MVC.
Introduction
We all know the benefit and beauty of GridView in ASP.NET Web Form. This is the best data control in ASP.NET MVC to quickly list the data from the database without specifying columns, table format etc. This was missing in ASP.NET MVC as it has not server side control like GridView.
Using the code
The good thing here is that we can still use the GridView of System.Web.UI.WebControls namespace in ASP.NET MVC and populate with data and get it rendered in the ASP.NET MVC view. Here is how the action method looks like
The Controller
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 this action method, we have first instantiated the GridView control and set its data source and called DataBind method that will bind the data from the data source.
Next, we are using StringWriter
and HtmlTextWriter
to render the GridView content string into the StringWriter
. The same is being set to the ViewBag.GridViewString.
The View
The View looks like below that simply use @Html.Raw method to write the content of the ViewBag.
@{ ViewBag.Title = "ListDataInGridView"; }
<h2>List Data In GridView</h2>
@Html.Raw(ViewBag.GridViewString)
Using @Html.Raw method is important as without this, it will simply render the HTML encoded characters of the GridView content string.
Conclusion
One of the most frequently used approach of listing the data was missing in ASP.NET MVC, thanks to GridView control that still works in ASP.NET MVC and can be used.
Hope this article was useful. Do subscribe for RSS feed and write your comments, suggestion. For more real time ASP.NET MVC tips and tricks,
click here.