Updated on Kisan Patel
In this article, you will learn how to rendering tabular data using WebGrid helper component in ASP.NET MVC.
we can use WebGrid helper to display data in tabular form. The WebGrid helper supports options for formatting, paging through the data, and for letting users sort just by clicking a column heading.
@{ var grid = new WebGrid(data); } @grid.GetHtml()
Lets create new ASP.NET MVC 5 application and name it to “MvcWebGridDemo” then add the Student
Model class and DbContext
class as shown in below code:
public class Student { public int Id { get; set; } public string Name { get; set; } public int RollNo { get; set; } public string Course { get; set; } } public class StudentContext : DbContext { public DbSet Students { get; set; } }
Next, add the ConnectionStrings in the web.config file:
<connectionStrings> <add name="StudentContext" providerName="System.Data.SqlClient" connectionString="Data Source=.SQLExpress;Initial Catalog=Test;Integrated Security=SSPI;" /> </connectionStrings>
Now, create HomeController and add the below line of code. In HomeController
I have set up an ASP.NET MVC action Index that simply passes an IEnumerable<Student>
to the Index view.
public class HomeController : Controller { // // GET: /Home/ public ActionResult Index() { using (StudentContext _db = new StudentContext()) { return View(_db.Students.ToList()); } } }
Next, create Views/Home/Index.cshtml view and includes the following Razor code, which renders the grid as shown in below screenshot:
Index.cshtml
@model IEnumerable<NewWebGrid.Models.Student> @{ ViewBag.Title = "Web Grid Demo"; } <h2>Web Grid Demo</h2> <div> @{ WebGrid grid = new WebGrid(Model, defaultSort: "Name", rowsPerPage: 5); } @grid.GetHtml() </div>
Now, run the Application and you will see below output…