In this article, you are going to learn how to quickly list the data from the database into Grid in ASP.NET MVC. 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.
The good thing here is that you 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, you 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, you have to use 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.
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.