You are on page 1of 3

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
1. @model List<Employee> 2. @{ 3. View.Title = "Employee List"; 4. } 5. @{ 6. 7. var grid = new WebGrid(source: Model, 8. defaultSort: "FirstName", 9. rowsPerPage: 3); 10. } 11. <p> 12. <h2>Employee List</h2> 13. <div id="grid"> 14. @grid.GetHtml( 15. tableStyle: "grid", 16. headerStyle: "head", 17. alternatingRowStyle: "alt", 18. columns: grid.Columns( 19. grid.Column("FirstName"), 20. grid.Column("LastName"), 21. grid.Column("Salary",format:@<text>$@item.Salary</text> ) 22. ) 23. ) 24. </div> 25. </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.
1. 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
1. public class Employee 2. { 3. public string FirstName { get; set; } 4. public string LastName { get; set; } 5. public double Salary { get; set; } 6. public static List<Employee> GetList() 7. { 8. List<Employee> employees = new List<Employee>{ 9. new Employee { FirstName="Rahul", LastName="Kumar", Salary=45000}, 10. new Employee { FirstName="Jose", LastName="Mathews", Salary=25000}, 11. new Employee { FirstName="Ajith", LastName="Kumar", Salary=25000}, 12. new Employee { FirstName="Scott", LastName="Allen", Salary=35000}, 13. new Employee { FirstName="Abhishek", LastName="Nair", Salary=125000} 14. }; 15. return employees; 16. } 17. }

Action Method
1. public ActionResult Index() 2. { 3. var empoyees = Employee.GetList(); 4. return View(empoyees); 5. }

The screen shot of the view page is shown in the below. The data is displayed with paging and sorting functionality.

You might also like