Search code examples
kendo-uikendo-gridkendo-asp.net-mvckendo-window

Using a custom window with ajax form to add new grid row


I need to create a more advanced method of adding new elements to a kendo grid, so in short I have replicated the following example as it does exactly what I needed: https://github.com/telerik/ui-for-aspnet-mvc-examples/tree/master/window/KendoWindow-Ajax-Form

And it works just fine. Only difference is the new row is added in it's correct spot in the grid, and not on the top as per usual. How can I, using the example linked to, place the new row on the top?

(I'm thinking it's not necessary to show my code here as it very closely resembles the code given in the link above)


Solution

  • Ended up finding the solution myself eventually. Going by the example in the link I made in the original post, this is what I did: Firstly when a new "order" is made, I make sure that the model returned in the "Create" method in OrdersDataController has an ID from when the model is added to the DB. So when this part gets executed in "_OrdersCreate.cshtml":

    @if (Model != null && ViewData.ModelState.IsValid)
    {
        <script>
            closeCreatePopup();
        </script>
    }
    

    I send information on the new Order created. So to that end I have modified "closeCreatePopup()" to handle arguments. So for the finished results I will just use a piece of code from my own project, the following is my implementation of "closeCreatePopup()":

    function closeCreateEmployeeWindow(name, rHPersonID, personID, organizationID) {
        if (name !== undefined
            && rHPersonID !== undefined
            && personID !== undefined
            && organizationID !== undefined) {
    
            var grid = $("#grid").data("kendoGrid");
            grid.dataSource.insert({ Name: name, RHPersonID: rHPersonID, PersonID: personID, OrganizationID: organizationID });
            grid.dataSource.sync();
        }
    
        var wnd = $("#createEmployeeModal").data("kendoWindow");
        wnd.refresh({ url: '@Url.Action("CreateEmployee", "Employee", new { Area = "Administration" })' });
        wnd.close();
    }
    

    The important part is this:

    var grid = $("#grid").data("kendoGrid");
    grid.dataSource.insert({ Name: name, RHPersonID: rHPersonID, PersonID: personID, OrganizationID: organizationID });
    grid.dataSource.sync();
    

    What is happening here is I use the "insert" method from the grid, and add a new object. "Insert" inserts the new object to the very top of the grid. Remember to call the "sync" method right after.

    By doing it like this, the normal "create" method built into the grid is replicated.