Updated on Kisan Patel
In previous tutorial, you learn how to display data in tabular format using WebGrid in ASP.NET MVC. Now, In this tutorial, you will learn how to customize the display of this data in the following ways:
Before going to this tutorial you must read the Using WebGrid in ASP.NET MVC article.
In this steps, you will use the WebGrid helper options to format individual columns. Now, open the Index.cshtml view and replace the existing marku with the following:
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( columns: grid.Columns( grid.Column("Name", "Student Name"), grid.Column("RollNo", "Roll No"), grid.Column("Course", "Subject", format:@<i>@item.Course</i>) ) ) </div>
This example is like the previous one, except that when you render the grid in the body of the page by calling grid.GetHtml, you are specifying both the columns to display and how to display them. The following code shows how to specify which columns to display and the order in which they should be displayed:
@grid.GetHtml( columns: grid.Columns( grid.Column("Name", "Student Name"), grid.Column("RollNo", "Roll No"), grid.Column("Course", "Subject", format:@<i>@item.Course</i>) ) )
To tell the helper which columns to display, you must include a columns parameter for the GetHtml method of the WebGrid helper, and pass in a collection of columns.
The below example for the Price column shows another variation of how to specify the format property:
grid.Column("Price", format:@<text>$@item.Price</text>)
This again specifies some HTML markup to render, and adds a dollar sign ($) before the column value.
Now, view the page in the browser you will see below ouput:
If you want to specifying how individual columns should be displayed, you can format the whole grid. To do so, you define CSS classes that specify how the rendered HTML table will look.
Lets open the Index.cshtml view and replace the existing marku with the following:
Index.cshtml
@model IEnumerable<NewWebGrid.Models.Student> @{ ViewBag.Title = "Web Grid Demo"; } <h2>Web Grid Demo</h2> <link href="~/Content/bootstrap.min.css" rel="stylesheet" /> <script src="~/Scripts/jquery-1.9.1.min.js"></script> <script src="~/Scripts/bootstrap.min.js"></script> <div> @{ WebGrid grid = new WebGrid(Model, defaultSort: "Name", rowsPerPage: 5); } @grid.GetHtml( tableStyle: "table table-bordered table-hover", alternatingRowStyle: "info", columns: grid.Columns( grid.Column("Name", "Student Name"), grid.Column("RollNo", "Roll No"), grid.Column("Course", "Subject", format:@<i>@item.Course</i>) ) ) </div>
In above code, the grid.GetHtml
method assigns table table-bordered table-hover
, info
styles to various elements of the grid using the tableStyle
, headerStyle
, and alternatingRowStyle
parameters.