This is a migrated thread and some comments may be shown as answers.

Change data URL on MVC Grid

10 Answers 1052 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Richard Averett
Top achievements
Rank 1
Richard Averett asked on 14 Aug 2012, 05:29 AM
I have a MVC Grid which is loading fine on the initial load. It uses the following code:

.DataSource(dataSource => dataSource 
        .Ajax()
        .PageSize(100)
    .Read(read => read.Action("AccountByType", "Organization", new { AccountType = 1 }))
)

I can successfully refresh the grid by calling the following:

$("#AccountGrid").data("kendoGrid").dataSource.read();

However, I need to change the query value that is passed in based on different selections the user makes on the page. So for example, I need to change the AccountType from 1 to 2 and refresh the grid. I tried the following:

$("#AccountGrid").data("kendoGrid").dataSource.options.transport.read.url = "/Organization/AccountByType?AccountType=2";
$("#AccountGrid").data("kendoGrid").dataSource.read()

But it doesn't work. Any suggestions on how to make this work?



10 Answers, 1 is accepted

Sort by
0
Petur Subev
Telerik team
answered on 14 Aug 2012, 11:04 AM
Hello Richard,

Basically in such scenarios when you want to change the parameters send to the server dynamically on the client, you should use the Data method to specify a function which result will be send to the server.

http://docs.kendoui.com/api/framework/datasource#transport.read.data-object|string|function


Kind Regards,
Petur Subev
the Telerik team
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
0
Andrew
Top achievements
Rank 1
answered on 20 Aug 2012, 08:27 AM
Hi Richard/Petur,

I have exactly the same issue, i am using razor syntax to build the grid on the page, please see the value OrgID=62, once this control is rendered how do i change the 62, i have tried all sorts of ways of doing this and no joy, also Petur, you said we should use a javascript datasource accorind to you link provided, but how do you changes this if using razor syntax. i am quite shocked at the lack of documentation regarding doing this, this should be a basic feature and the method for achieving this should be freely available.

@{Html.Kendo().Grid<EasyAssets.Model.DTO.LoadDTO>()
    .Name("LoadList")
    .Columns(columns =>
    {
        columns.Bound(p => p.LoadID).Groupable(false).Visible(false);
        columns.Bound(p => p.LoadNumber).Width("50px");
        columns.Bound(p => p.ExpectedStartDate).Format("{0:d}").Width("80px");
        columns.Bound(p => p.fleetnumber).Width("50px");
        columns.Bound(p => p.Organisation).Width("120px");
        columns.Bound(p => p.user).Width("50px");
        columns.Bound(p => p.loadStatus).Width("50px");
        columns.Command(command => command.Custom("Print").Click("Print")).Width("50px");
        columns.Command(command => command.Custom("ConfirmLoad").Click("Confirm")).Width("50px");


    })
    .Sortable()
    .Pageable()
    .Scrollable()
    .ClientDetailTemplateId("detailTemplate")
    .DataSource(dataSource => dataSource
        .Ajax()
        .Read(read => read.Action("LoadListBinder", "PlannedTrips", new { OrgId = "62" }))
        .PageSize(15)
    )
    .HtmlAttributes(new { style = "height: 550px" })
    .Selectable(selectable => selectable.Mode(GridSelectionMode.Single))
    .Render();
}
0
Jim.Mills
Top achievements
Rank 1
answered on 21 Aug 2012, 09:40 PM
I am having a similar issue.  I am using the .Data("methodname()") and it works the first time, but when I call the .read() action in javascript, it never calls the Data method again?

My View: 
<input type="button" value="Ajax" onClick="onRetrieve()" />


.DataSource(datasource => datasource
    .Ajax()
    .ServerOperation(false)
    .Read(read => read.Action("_GetGridList","Log")
                      .Data("GetCriteria()"))

and here is my javascript functions:
function GetCriteria() {
    var obj = {
        StartDate : $("#StartDate").val(),
        EndDate : $("#EndDate").val(),
        SelectedApplication: $("#SelectedApplication").val(),
        SelectedMachine: $("#SelectedMachine").val(),
        SelectedEnvironment: $("#SelectedEnvironment").val(),
        SelectedUserName: $("#SelectedUserName").val(),
        ErrorID: $("#ErrorID").val(),
        SearchValue: $("#SearchValue").val()
    };
    return obj;
};

function onRetrieve() {
    var grid = $("#GridErrorList").data("kendoGrid");
    grid.dataSource.read();
};


and here is my controller...
[HttpPost]
     public ActionResult _GetGridList([DataSourceRequest] DataSourceRequest request, SearchCriteria CriteriaModel)
         {
 
         ViewModel model = new ViewModel();
         model.Criteria = CriteriaModel;
 
         ValidateModel(CriteriaModel);
         model.Result = SearchForErrors(model.Criteria);
         DataSourceResult result = model.Result.Items.ToDataSourceResult(request);
         return Json(result);
 
         }


0
Petur Subev
Telerik team
answered on 22 Aug 2012, 06:24 AM
Hi Jim,

You should pass only the name of the function to the Data method - without the brackets. 
.Read(read => read.Action("_GetGridList","Log")
                      .Data("GetCriteria"))


Regards,
Petur Subev
the Telerik team
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
0
Andrew
Top achievements
Rank 1
answered on 22 Aug 2012, 06:33 AM
Hi Jim,

I havent seen your method before, can you post an example or link of how to setup a model that accepts the criteria you are posting. sorry but i am very new to both kendo and MVC, battleing to get my head around things, been in webforms dev for a long time.

Regards
Andrew
0
Jim.Mills
Top achievements
Rank 1
answered on 22 Aug 2012, 08:38 PM
Thank you Peter, that worked great!  I appreciate the quick response.  I have another question, if you don't mind me asking.  The additional data that I am sending to the controller is basically from the model that was sent to the view.  Is there a way I can grab that directly and send it as an object to the controller, or do I have to do as the code above is written and generate my own object and fill it?

==========================
Andrew..., I'm very new to MVC and Javascript myself.  I'm still working on it, but basically I have created a Model that has the search criteria on it (simple class with the appropriate properties).  This gets generated in the view the first time using standard Razor syntax.

I started off by putting these criteria inputs in a form and including a submit button.  This worked great and sent the criteria to the controller and I did my search and returned the same model, except the results were attached and I bound them to the Kendo Grid using razor syntax (no ajax).  I didn't like this because I lost the status of the Grid's (sort, group, etc.) because it was basically a new call to the server each time, so my next step was to change the page so that the Grid was filled and refreshed via ajax.

That is what the code above is doing.  When a button is clicked, it calls my Retrieve() java script function which executes the Grid.DataSource.Read() method.  The Read Action is defined to go to a particular action on a particular controller (see above).  The Read Action also has a .Data() attribute that allows you to specify a javascript function to generate additional data to be sent to the controller.  This is where I am generating a basic object and filling the parameters from my "Search Criteria" form.  
Originally, I wanted to just grab the form (since it matched my Model exactly) out of the Dom and send it, but I couldn't get it to serialize correctly, so I am instead creating a javascript object that matches my model, filling it with the values from the Dom using jQuery  and sending it.  This seems to work good.  It's still in progress, but if you need more help feel free to contact me and I can perhaps help out a bit.  It's no fun to struggle alone! :)

0
Dylan
Top achievements
Rank 1
answered on 12 Sep 2012, 02:22 PM
Richard,

You were correct but.. Kendo stores the original read url in options.dataSource.transport.read.url
But then read() gets it from dataSource.transport.options.read.url

var grid = $("#AccountGrid").data("kendoGrid");

grid.dataSource.transport.options.read.url = "/Organization/AccountByType?AccountType=2"
grid.dataSource.read()
0
Randy
Top achievements
Rank 1
answered on 07 Mar 2017, 04:45 PM

Is it possible to dynamically change the datasource for the MVC side of things? I'm getting data back, but I'm not able to get the data to the page? my code looks like this:



js:



<script>

    $(document).ready(function () {
        $('#year').click(function () {
         
            var storeNumber = 1017
;
            var blahGrid = new kendo.data.DataSource({
                transport: {
                    read: {
                        url: "/Store/Employees",
                        data: { storeNumber: storeNumber}
                    }
                },
                schema: {
                    model: {
                        id: "EmployeeID",
                        fields: {
                       "EmployeeID" : { type: "string" }
                        }
                    }
                }
            });
        
          
            var grid = $("#EmployeeGridAll").data("kendoGrid");
            grid.setDataSource(blahGrid);

         

        });
    });

</script>





razor:



@(Html.Kendo().Grid<EmployeeVM>()
    .Name("EmployeeGridAll")

    .Columns(columns =>
    {
        columns.Bound(c => c.HireDate);
        columns.Bound(c => c.EmployeeName);
        columns.Bound(c => c.EmployeeID);
        columns.Bound(c => c.EmployeeStatus);
    })
    .NoRecords("Please select a date range above.")
    .Pageable(pageable => pageable.ButtonCount(5))
      //.Selectable(selectable => selectable
      //  .Mode(GridSelectionMode.Single))
      .DataSource(dataSource => dataSource
        .Ajax()
        .Read(read => read.Action("Employees", "Store"))
        .PageSize(15))
      //.Events(e => e.Change("datasource_change")).a
      .HtmlAttributes(new { style = "height:550px;width:100%;", id = "GridAll" })
      .Sortable()
      .Scrollable()
      .Filterable()
      .Groupable()
      .Mobile()
)





what I'm wanting to do is change the data source based upon a button click. what am i missing here?

 

Thanks.

0
Randy
Top achievements
Rank 1
answered on 07 Mar 2017, 04:48 PM
Is it possible to dynamically change the datasource for the MVC side of things? I'm getting data back, but I'm not able to get the data to the page? my code looks like this:
 
 
js:
 
 
<script>
 
    $(document).ready(function () {
        $('#year').click(function () {
          
            var storeNumber = 1017
;
            var blahGrid = new kendo.data.DataSource({
                transport: {
                    read: {
                        url: "/Store/Employees",
                        data: { storeNumber: storeNumber}
                    }
                },
                schema: {
                    model: {
                        id: "EmployeeID",
                        fields: {
                       "EmployeeID" : { type: "string" }
                        }
                    }
                }
            });
         
           
            var grid = $("#EmployeeGridAll").data("kendoGrid");
            grid.setDataSource(blahGrid);
 
          
 
        });
    });
 
</script>
 
 
 
razor:
 
 
@(Html.Kendo().Grid<EmployeeVM>()
    .Name("EmployeeGridAll")
 
    .Columns(columns =>
    {
        columns.Bound(c => c.HireDate);
        columns.Bound(c => c.EmployeeName);
        columns.Bound(c => c.EmployeeID);
        columns.Bound(c => c.EmployeeStatus);
    })
    .NoRecords("Please select a date range above.")
    .Pageable(pageable => pageable.ButtonCount(5))
      //.Selectable(selectable => selectable
      //  .Mode(GridSelectionMode.Single))
      .DataSource(dataSource => dataSource
        .Ajax()
        .Read(read => read.Action("Employees", "Store"))
        .PageSize(15))
      //.Events(e => e.Change("datasource_change")).a
      .HtmlAttributes(new { style = "height:550px;width:100%;", id = "GridAll" })
      .Sortable()
      .Scrollable()
      .Filterable()
      .Groupable()
      .Mobile()
)
 
 
 
what I'm wanting to do is change the data source based upon a button click. what am i missing here?
0
Stefan
Telerik team
answered on 10 Mar 2017, 10:55 AM
Hello Randy,

The demonstrated approach should work as expected.

I made an example simulating a similar approach which is working as expected.

Please check the attached file.

Also, please ensure that after the new dataSource is set the correct request is made to the server and the data is correctly returned.

Regards,
Stefan
Telerik by Progress
Try our brand new, jQuery-free Angular 2 components built from ground-up which deliver the business app essential building blocks - a grid component, data (charts) and form elements.
Tags
Grid
Asked by
Richard Averett
Top achievements
Rank 1
Answers by
Petur Subev
Telerik team
Andrew
Top achievements
Rank 1
Jim.Mills
Top achievements
Rank 1
Dylan
Top achievements
Rank 1
Randy
Top achievements
Rank 1
Stefan
Telerik team
Share this question
or