Store calculated data in Column of Kendo Grid

2 posts, 0 answers
  1. Austin
    Austin avatar
    24 posts
    Member since:
    Jun 2015

    Posted 10 Feb 2016 Link to this post

    What I'm trying to do is display some data in a specific column that is calculated by using the data from another column.

    I currently have a function that returns the number of available licenses for the given 'Id' in JSON:

    function getAvailableLicenses(id) {
        var url = "/Host/Organization/AvailableLicenses/" + id;
        $.get(url, function (data) {
            return data.AvailableLicenses;
        });
    }

     

    How do I go about displaying the number that is returned in a column named "AvailableLicenses"?

    Here is my current Grid:

    $("#OrganizationGrid").kendoGrid({
        dataSource: viewModel.get("orgDataSource"),
        filterable: {
            extra: false
        },
        sortable: true,
        pageable: true,
        columns: [
            { field: "Id", hidden: true },
            { field: "Name", template: "<a href='/Host/Organization/Detail/#:Id#'>#:Name</a>"},
            { field: "LicenseNumber", title: "Number of Licenses" },
            { field: null, title: "Available Licenses", template: "#= getAvailableLicenses(Id) #" },
            { field: "LicenseExpiration", title: "License Expiration", format: "{0:MM/dd/yyyy}" },
            { field: "State" },
            { field: "Active" }
        ],
        editable: false
    });

     

    As you can see, I tried to create a null column with a template that calls the function for the given 'Id'.

    By using Fiddler, I can see that the function is indeed being called for all of the rows, but the 'AvailableLicenses' column just displays "undefined" for every row.

    Is there something I'm missing here to get this to work?

  2. Austin
    Austin avatar
    24 posts
    Member since:
    Jun 2015

    Posted 11 Feb 2016 in reply to Austin Link to this post

    Found a solution myself. It was because I was trying to return an Ajax call that was not yet completed so it was always returning defined.

    I change my function to the following to get it to work properly:

    function getAvailableLicenses(id) {
        var url = "/Host/Organization/AvailableLicenses/" + id;
        var reult = "";
     
        $.ajax({
            url: url,
            async: false,
            success: function (data) {
                result = data.AvailableLicenses;
            }
        });
         
        return result;
    }

     

    I also decided to parse the DataSource rather than use a template as it's a little cleaner to do it this way:

    schema: {
        parse: function (response)
            for (var i = 0; i < response.length; i++) {
                response[i].AvailableLicenses = null;
                response[i].AvailableLicenses = getAvailableLicenses(response[i].Id);
            }
        return response;
    }

Back to Top