In my previous post How to use grid view in MVC I discussed very basic use of WebGrid extension in MVC applications to display a grid view. In real life application you need a little bit more control on how the grid view is rendered. In this post I will discuss about how to control the columns that are displayed in grid.
Source property of WebGrid is used to attach data collection that is going to be used to display grid. By default WebGrid will display all the properties of the collection object as columns in the grid. Most of the time you are not looking into rendering all the properties as columns. And some time you need to display column text by manipulating some existing data and styling it differently. This means we need a way to pick and choose the columns or properties that should be displayed as columns in grid. There are two options in WebGrid to control display of columns.
WebGrid object constructor takes an argument to set collection of column names that are going to rendered. This collection is name of the properties of the object.
@model IQueryable@{ var columns = new List<string>() { "Title", "Author" }; var grid = new WebGrid(source: Model, columnNames: columns, defaultSort: "DateCreated", rowsPerPage: 25, canSort: true); }
As you can see from above code, I have created a list of string with two values in it. Then this collection object has been assigned to columnNames constructor parameters. This is a very quick way to specific the columns. This method does not provide very fine control on display of individual columns in grid view. Following image shows how my sample grid view looks like.
If you are looking for greater control on display of columns in grid view, then you will need to set collection of WebGridColumn objects in GetHtml method during rendering of view.
<div> @grid.GetHtml( columns: grid.Columns( grid.Column("Title", "Blog title"), grid.Column("Author", "Blog Author"), grid.Column("DateCreated", "Created On", @<i>@item.DateCreated.ToString("yyyy-MM")<i>, "mystyle", false) ) ) <div>
Above code snippet shows how to set this collection. WebGridColumn object exposes following properties that allows you to control behavior of each column.
As you can see WebGrid provides you full control on controlling on selecting what individual columns to display in your MVC grid view and how to manipulate each control's rendering. In subsequent posts, I will discuss more about customization of MVC grid.
How to plan CCSP Exam preparation
Develop a MongoDB pipeline to transform data into time buckets
Alert and Confirm pop up using BootBox in AngularJS
AngularJS Grouped Bar Chart and Line Chart using D3
How to lock and unlock account in Asp.Net Identity provider
2024 © Byteblocks, ALL Rights Reserved. Privacy Policy | Terms of Use