0

i have a webgrid in which i want to place a conditional statement on the column data that i will have?

is it possible and if yes, can you provide an example?

EDIT

Just a snippet

grid.Column("Status","Status",canSort: true)

if the value of the status is "correct", i want to display an image instead of the text.

sameer
  • 220
  • 2
  • 6
  • 18

3 Answers3

1

Source

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("Name"),
grid.Column("Password"),
grid.Column("EmailAddress") ))

}
else{

@grid.GetHtml(columns: grid.Columns(

grid.Column("Name")
// 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…

@grid.GetHtml(
    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")
    )
)
Yasser Shaikh
  • 46,934
  • 46
  • 204
  • 281
1

A less tedious an easier readable code (and only year and a half later).

var columnsToAdd = new List<WebGridColumn>();
///here add yout collumns according to conditions

@grid.GetHtml(columns: columnsToAdd.ToArray())
lew
  • 77
  • 4
  • 11
0

If I'm understanding your question correctly, you would want to put an 'if' statement in your view. Something like:

@{
    var option1 = true;
    var option2 = false;
}
@if(option1){
    <div id="grid1">
        @grid.GetHtml(
            tableStyle: "grid",
            headerStyle: "head",
            alternatingRowStyle: "alt",
            columns: grid.Columns(
                grid.Column("firstColumn"),
                grid.Column("secondColumn")
            )
        )
    </div>
} else if (option2) {
    <div id="grid2">
        @grid.GetHtml(
            tableStyle: "grid",
            headerStyle: "head",
            alternatingRowStyle: "alt",
            columns: grid.Columns(
                grid.Column("firstColumn"),
                grid.Column("secondColumn"),
                grid.Column("thirdColumn")
            )
        )
    </div>
} else {
    <div id="grid3">
        No grid
    </div>
}
barbajoe
  • 547
  • 5
  • 15