kendo-uikendo-gridkendo-mvvmkendo-listview

Telerik Kendo UI with MVVM


I have one Kendo UI Grid in my view page (MVVM Concept). Bind the data from view model. When I reduce the page size.

Kendo UI grid change to Kendo UI Listview. See this image:

Grid view change to List view

How can I do this?


Solution

  • Define one single DataSource for both Grid and ListView.

    var ds = {
        data    : ...,
        pageSize: 10,
        schema  : {
            model: {
                fields: {
                    Id       : { type: 'number' },
                    FirstName: { type: 'string' },
                    LastName : { type: 'string' },
                    City     : { type: 'string' }
                }
            }
        }
    };
    

    Then define both a DIV for the Grid and for the ListView:

    <div id="grid"></div>
    <div id="list"></div>
    

    And initialize the Grid and the ListView:

    $("#grid").kendoGrid({
        dataSource: ds,
        columns   :
        [
            { field: "FirstName", width: 90, title: "First Name" },
            { field: "LastName", width: 200, title: "Last Name" },
            { field: "City", width: 200 }
        ]
    });
    
    $("#list").kendoListView({
        dataSource: ds,
        template : $("#template").html()
    });
    

    Now, what you should do is display one or the other depending on the width:

    // Display Grid (and hide ListView)
    $("#grid").removeClass("ob-hidden");
    $("#list").addClass("ob-hidden");
    
    // Display ListView (and hide Grid)
    $("#grid").addClass("ob-hidden");
    $("#list").removeClass("ob-hidden");
    

    Where CSS class ob-hidden is:

    .ob-hidden {
        display: none;
        visibility: hidden;
        width: 1px;
    }
    

    Now, the only remaining question is invoke one or the other depending on the width. You can user jQuery resize event for detecting changes.

    So, enclose both ListView and Grid in a DIV with id container:

    <div id="container">
        <div id="grid"></div>
        <div id="list" class="ob-hidden"></div>
    </div>
    

    and define the resize handler as:

    $("window").on("resize", function(e) {
        var width = $("#container").width();
        console.log(width);
        if (width < 300) {
            console.log("list");
            $("#grid").addClass("ob-hidden");
            $("#list").removeClass("ob-hidden");
        } else { 
            console.log("grid");
            $("#grid").removeClass("ob-hidden");
            $("#list").addClass("ob-hidden");
        }
    });
    

    IMPORTANT: Whatever you do for getting this same result, please, don't create and destroy the Grid and the ListView each time there is a resize. This a computationally expensive operation.

    See it in action here: http://jsfiddle.net/OnaBai/JYXzJ/3/