How do I attach function to kendo grid after it initialized?

2.7k views Asked by At

I have a Kendo Grid and I have JavaScript function “getFilters”. The “getFilters” function is scoped function defined in document ready. Currently the grid is calling “getFilters” like below. But this doesn’t work because “getFilters” gets initialized after the grid initialization. So im getting error 0x800a1391 - JavaScript runtime error: 'getFilters' is undefined

I don’t want to make “getFilters” function as global. So How do I attach “getFilters” to the dasource after grid is initialized? I would like to do that in Document Ready

@(Html.Kendo().Grid<MyModel>()
    .Name("Grid")                    
        col.Bound(p => p.State).Title("State");            
        col.Bound(p => p.BatchStatus).Title("Status");
    })
    .AutoBind(false)
    .Pageable()
    .Sortable()                
    .DataSource(dataSource => dataSource
        .Ajax()                    
        .Read(read => read
            .Action("GetData", "MyController")
            .Data("getFilters"))
        .ServerOperation(false))
)

JavaScript document ready function

$(function () {

  function getFilters() {
    return SomeJSON;
  }


  var ds = $("#Grid").data("kendoGrid").dataSource;

      //How do i attach getFilters function to dataSource here?


})
2

There are 2 answers

0
LP13 On BEST ANSWER

I found the answer, this may help others. Here how you can attach function in document ready

  var grid = $("#grid").data("kendoGrid");
  grid.dataSource.transport.options.read.data = getFilters;

And then call read() to reload the grid. Every time you call read() the attached function "getFilters" will get executed.

  grid.dataSource.read();
4
Amal Dev On

You should move out the function getFilters from the document ready and place it inside the script tag above or below the grid initialization part

<script>
function getFilters() {
    return SomeJSON;
  }
</script>


@(Html.Kendo().Grid<MyModel>()
    .Name("Grid")                    
        col.Bound(p => p.State).Title("State");            
        col.Bound(p => p.BatchStatus).Title("Status");
    })
    .AutoBind(false)
    .Pageable()
    .Sortable()                
    .DataSource(dataSource => dataSource
        .Ajax()                    
        .Read(read => read
            .Action("GetData", "MyController")
            .Data("getFilters"))
        .ServerOperation(false))
)

Please refer here for a similar question in SO