Conditionally Display Columns
Environment
| Product | Progress® Kendo UI® Grid for jQuery | UI for ASP.NET MVC |
Description
How can I hide some of the Grid columns and conditionally display Edit and Delete buttons?
Solution
The column configuration of the Grid for ASP.NET MVC has a Hidden() (columns.hidden) property that expects a Boolean value which can be used for such purposes.
The following example demonstrates how to pass a value in the ViewBag for a key and give it a true or false value in the controller, and then access it in the Razor template.
To individually fine-tune a command, use the command visible function.
Razor Example
The following snippet passes an IsAdmin flag from the controller through ViewBag and uses it to toggle column visibility and the command column in the Razor template.
public ActionResult Index()
{
ViewBag.IsAdmin = true;
return View();
}
@(Html.Kendo()
.Grid<DetailGrids.Models.Inventory>()
.Name("InvGrid")
.Columns(columns =>
{
columns.Bound(p => p.OnOrder).Width(125).Hidden(ViewBag.IsAdmin);
columns.Command(command => { command.Edit(); command.Destroy(); }).Hidden(!ViewBag.IsAdmin);
})
)
JavaScript Example
The following snippet initializes a Grid in pure JavaScript and sets hidden: !isAdmin on the command column to control its visibility based on a boolean variable.
var isAdmin = false;
$("#grid").kendoGrid({
columns: [
{ field: "name" },
{ command: [{ name: "edit" }], hidden: !isAdmin }
],
editable: "popup",
dataSource: [ { name: "Jane" }, { name: "Bill" } ]
});