In this example I’ll show you that how to render the basic WebGrid in the Razor View. I’ll use the Sample Employee SQL Database in the examples. I believe you have setup the all prerequisites for Walk-through of WebGrid in MVC 4.
Let’s start with controller, see the action ‘webgrid_demo’:
namespace MvcApplication1.Controllers { public class HomeController : Controller { private EmployeeDatabaseEntities _dbcontext = new EmployeeDatabaseEntities(); public ActionResult Index() { ViewBag.Message = "Click on example to load."; return View("Index"); } public ActionResult webgrid_demo() { Response.CacheControl = "no-cache"; _dbcontext = new EmployeeDatabaseEntities(); var model = _dbcontext.tbl_Employee; return View("WebGrid", model.ToList<tbl_Employee>()); } } }
From the controller I am passing the model in the form of List
You will also get the others functionalists with using the simple two line of code such as paging and sorting; the column headers are rendered as Link to enable the sorting. Simply you can handle paging, sorting, custom styles and behavior of the WebGrid in your own way.
@model List<MvcApplication1.tbl_Employee> @{ ViewBag.Title = "Working with Web Grid in MVC"; } @section featured { <section class="featured"> <div class="content-wrapper"> <hgroup class="title"> <h1>@ViewBag.Title.</h1> <h2>@ViewBag.Message</h2> </hgroup> </div> </section> } <div id="EmployeeViewGrid"> @{ var grid1 = new WebGrid(source: Model, canPage: true); @grid1.GetHtml(); } </div> @section Scripts { @Scripts.Render("~/bundles/jqueryval"); }
The WebGrid have the following main properties:
Source – Source of the data Usually the model passed by the controller action (See in the example we are passing the model.ToList>tbl_Employee<() in the form of List>t<).
DefaultSort – this property indicates how the data will be sorted. ( we are not using this property in the example. Try using this property like as:
var grid1 = new WebGrid(source: Model,DefaultSort:"Name", canPage: true);
RowsPerPage – Number of records that will be shown on table.
CanPage – this property allows paging. By default the value is true. If you want to stop paging, just use the property with false value like as:
var grid1 = new WebGrid(source: Model, canPage: false);
CanSort – Allows sorting by clicking on column’s header. The value of this property will be true or false.
If you will face any problem. Please let me know.