Search code examples
jqueryrazorkendo-uikendo-grid

Condition based page size and filters of Kendo Grid


Is there any way to control the filters and page size options of my Kendo Grid?

Ex: I've a Kendo grid with some filters and page size. Now I want to remove some of the filters for selected columns. Also page size based on login (or some condition).

Is there any way to handle this? from controller or from my view?


Solution

  • Instead of changing the filters dynamically, and since in your case you only need to change it depending on the login, the idea would be creating the grid with the right values. I.e., emit the code from the server but use as value for filterable and pageSize a JavaScript variable that gets its value in execution time and depending on the user logged in.

    Example: I define a login form that when user clicks on a Login button it executes the Grid initialization that since then it is empty.

    Form:

    <div id="container">
        <div id="form" class="k-block">
            <div class="k-header">Login Form</div>
            <div>Login : <input id="user" type="text" data-role="autocomplete"/></div>
            <button class="k-button" id="doLogin">Login</button>
        </div>
    </div>
    

    JavaScript intercepting click on doLogin button:

    $("#doLogin").click(function() {
        ...
    });
    

    Code for reading user logged-in and setting the default value for pageSize and filterable or user specific value:

    var user = $("#user").val();
    // Default value
    var filterable = false;
    var pagesize = 5;
    // Specific value
    if (user == "OnaBai") {
        pagesize = 20;
        filterable = true;
    }
    

    Now, proceed with the initialization of the DataSource and the Grid. We will use filterable and pageSize JavaScript variables for the initialization.

    // pageSize is variable, the remaining code is the same no matter of the user
    var ds = new kendo.data.DataSource({
        pageSize: pagesize,
        transport: {
            ...
        },
        ...
    };
    
    // Create a DIV element and a Grid on it.
    var grid = $("<div id='grid'></div>").kendoGrid({
        dataSource: ds,
        filterable: filterable,
        ...
    });
    // Append Grid element to the correct place of the HTML page
    grid.appendTo($("#container"));
    

    See a running example here: http://jsfiddle.net/OnaBai/U9LQ4/1/