Using the WebGrid Helper in ASP.NET MVC 3 Beta
ASP.NET MVC 3 Beta is now supports to using ASP.NET Web Pages helpers in the Razor views. In this post, let us discuss on how to use WebGrid helper in our Razor view page of an ASP.NET MVC 3 application.
Let us create a view page using Razor syntax
- @model List<Employee>
- @{
- View.Title = "Employee List";
- }
- @{
- var grid = new WebGrid(source: Model,
- defaultSort: "FirstName",
- rowsPerPage: 3);
- }
- <p>
- <h2>Employee List</h2>
- <div id="grid">
- @grid.GetHtml(
- tableStyle: "grid",
- headerStyle: "head",
- alternatingRowStyle: "alt",
- columns: grid.Columns(
- grid.Column("FirstName"),
- grid.Column("LastName"),
- grid.Column("Salary",format:@<text>$@item.Salary</text>)
- )
- )
- </div>
- </p>
In the above code, we create an instance of WebGrid with data source as our Model object and we specified that default sort is FirstName for the sorting purpose and rowsPerPage specified for the paging functionality. The GetHtml method of the WebGrid object will renders an HTML table for the grid helper. Using the the grid.Columns, we can specify which columns to display and we can also apply formatting for the columns.
- grid.Column("Salary",format:@<text>$@item.Salary</text>)
The above code is applying a sign ($) before the column value Salary.
The below code block is showing our Model class and the Action method
Employee Class
- public class Employee
- {
- public string FirstName { get; set; }
- public string LastName { get; set; }
- public double Salary { get; set; }
- public static List<Employee> GetList()
- {
- List<Employee> employees = new List<Employee>{
- new Employee { FirstName="Rahul", LastName="Kumar", Salary=45000},
- new Employee { FirstName="Jose", LastName="Mathews", Salary=25000},
- new Employee { FirstName="Ajith", LastName="Kumar", Salary=25000},
- new Employee { FirstName="Scott", LastName="Allen", Salary=35000},
- new Employee { FirstName="Abhishek", LastName="Nair", Salary=125000}
- };
- return employees;
- }
- }
Action Method
- public ActionResult Index()
- {
- var empoyees = Employee.GetList();
- return View(empoyees);
- }
The screen shot of the view page is shown in the below. The data is displayed with paging and sorting functionality.