How to hide specific columns / values in webgrid MVC3 razor

In MVC 3 Razor, lot of people use webgrid for displaying their data from database in a tabular fashion. Now I came across a need to include a specific column of a webgrid only if one of my condition matches.

After looking around for sometime on the internet I did not find any neatly written article for this, so I have decided to take this task myself and here we are…

Here on check of a condition I am hiding my two columns Password and Email Address. By doing so, I can prevent my webgrid to show the column which I dont want to display for a particular condition.

var grid = new WebGrid(Model.User)

if(myConditionCanGoInHere) {

@grid.GetHtml(columns: grid.Columns(

grid.Column("EmailAddress") ))


@grid.GetHtml(columns: grid.Columns(

// Here I have not included Password and EmailAddress columns.


This is when you want to hide the full column, but what if you want to show the column and hide only specific values, then in that case what is to be done ? That too can be done, you can have a if else condition like the one showed below…

columns: grid.Columns(
grid.Column(header: "Edit", format: item => item.CanEdit ? Html.ActionLink("Edit","Edit","Person",new {id = item.PersonId},null) : Html.Raw("uneditable")),

grid.Column(columnName: "CanEdit", header: "Editable?"),
grid.Column(columnName: "DisplayName", header: "Display Name"),
grid.Column(columnName: "Email", header: "Email")