Pass additional parameters to Read ajax datasource method - MVC

12 Answers 33283 Views
Grid
Nirav
Top achievements
Rank 1
Nirav asked on 28 Mar 2013, 09:43 AM
Hi,

I want to pass an additional parameter to my Read ajax method from Grid along with currently passing the controller name and method name.

Currently I have something like below in my cshtml file:
.DataSource(dataSource => dataSource
            .Ajax()
            .PageSize(5)
            .Model(model => model.Id(m => m.Id))
            .Create(create => create.Action("Create", controllerName))
            .Read(read => read.Action("Read", controllerName))
            .Update(update => update.Action("Update", controllerName))
            .Destroy(delete => delete.Action("Delete", controllerName))
        )
And my Action method is below:
public ActionResult Read([DataSourceRequest] DataSourceRequest request)
{}

Please can you show my how to pass addtional parameter (i.e Id) in Grid for Read operation and how to handle it in corresponding Controller?

Thanks,
Nirav

12 Answers, 1 is accepted

Sort by
1
Dimiter Madjarov
Telerik team
answered on 28 Mar 2013, 12:43 PM
Hello Nirav,


You could pass additional data either using object route values
E.g.
.Read(read => read.Action("Products_Read", "Grid", new { name = "test", id = 2 }))

OR
via the Data method, which specifies a JavaScript function, which will return the additional parameters.
E.g.
.Read(read => read.Action("Products_Read", "Grid").Data("additionalInfo"))

function additionalInfo() {
    return {
        name: "test",
        id: 2
    }
}

In both cases, you should add the two additional parameters to you Action.
E.g.
public ActionResult Products_Read([DataSourceRequest] DataSourceRequest request, string name, int id) {...}

 

Kind regards,
Dimiter Madjarov
the Telerik team
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
Nirav
Top achievements
Rank 1
commented on 02 Apr 2013, 08:05 AM

Thanks Dimiter, It worked as expected.

But what if any of the additional parameter is optional? If we take your example then what if Id param is optional? How to handle it in 
.Read(read => read.Action("Products_Read", "Grid", new { name = "test", id = 2 }))

In my example below I may or may not pass Id. Means Id could be any integer value or it could be null.
.Read(read => read.Action("Read", controllerName. new { Id = 3 }))

I know the implementation part in controller class but not in cshtml.

Regards,
Nirav
Dimiter Madjarov
Telerik team
commented on 02 Apr 2013, 08:19 AM

Hi Nirav,


Since the parameter is optional in the current scenario, you should specify it's type to be nullable in the controller. 
E.g.
public ActionResult Products_Read([DataSourceRequest] DataSourceRequest request, int? id) {...}

 

Kind regards,
Dimiter Madjarov
the Telerik team
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
Nirav
Top achievements
Rank 1
commented on 02 Apr 2013, 10:25 AM

Hi Dimiter,

I understood your solution provided that I have to implement it in controller.

But since it is an interger I cannot assign null in Ajax Read action mentiond below. It gives a compilation error.
.Read(read => read.Action("Products_Read", "Grid", new { Id = null}))

Either I have to give it a non zero value or it should be 0 (zero). In this case in my controller I have to explicitely check if Id is 0 then perform normal operation and if Id is non zero perform specific operation.

I can do it the way I have explained above but I am finding any logical and clear solution.

Regards,
Nirav
Dimiter Madjarov
Telerik team
commented on 02 Apr 2013, 12:03 PM

Hello Nirav,


This is quote from my answer in the support thread.



If the parameter is defined as nullable in the controller and you don't want to pass it in the current scenario, you should just omit the RouteValues object.
E.g.
.Read(read => read.Action("Products_Read""Grid"))

otherwise, you could add the Id with an integer value.
E.g.
.Read(read => read.Action("Products_Read""Grid"new { Id = 5 }))



Nirav, it would be easier for us to provide you better support if we continue only one of the two threads (forum and support). If you need additional support, please reply only in the support thread or here in the forum if you think, that this information is useful for other customers too.

Wish you a great day!

 

Kind regards,
Dimiter Madjarov
the Telerik team
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
Nirav
Top achievements
Rank 1
commented on 02 Apr 2013, 12:38 PM

Hi,

If I omit the RouteValues it doesn't work.
Means for .Read(read => read.Action("Products_Read", "Grid")), if I pass the parameter or not, none of the below controller actions invoke.
public ActionResult Products_Read([DataSourceRequest] DataSourceRequest request)
public ActionResult Products_Read([DataSourceRequest] DataSourceRequest request, int id)

And if I use the below controller actions, each time whether I pass the id (in query string or as a parameter) or not, only the second action invokes.
public ActionResult Products_Read([DataSourceRequest] DataSourceRequest request)
public ActionResult Products_Read([DataSourceRequest] DataSourceRequest request, int? id)

I have closed the similar support ticket to allow discussion at one place and for all here on forum.

Thanks,
Nirav
Dimiter Madjarov
Telerik team
commented on 03 Apr 2013, 12:30 PM

Hi Nirav,


This behavior is expected in the current scenario, since the call to the Controller Actions is ambiguous. You should only define a single Action with the following signature
E.g.
public ActionResult Products_Read([DataSourceRequest] DataSourceRequest request, int? id) {...}

and perform an explicit check to determine if id is null or not. Additional information could be found on the internet.

 

All the best,
Dimiter Madjarov
the Telerik team
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
Vision Engineering
Top achievements
Rank 1
commented on 06 Aug 2013, 10:50 AM

Hi,
I have similar question.
I'm trying to pass serialized form as an additional parameter to Read ajax datasource method but no success, model isn't constructing.

Here is my Razor code:
<form id="form">
<div>
  @Html.EditorFor(model => model.FilterCriteria)
</div>
<div>
    @(Html.Kendo().Grid<MyGridRow>().Name("ResultGrid").HtmlAttributes(new
{
  style = "width: 100%; margin-top: 10px"
}).Columns(col => col.AutoGenerate(true)).Pageable(p => p.Refresh(true)).Sortable().Filterable().Selectable(selectable => selectable.Mode(GridSelectionMode.Single)).Resizable(resize => resize.Columns(true)).DataSource(ds => ds.Ajax().PageSize(15).Read(a => a.Action("GetGridData", "MyController").Data("getFilterCriteria").Type(HttpVerbs.Post))))
</div>
</form>
function getFilterCriteria() {
     var e = $('#form').serializeArray();
    return e;
 
  }
Here is code from MyController.cs:
[HttpPost]
        public ActionResult GetGridData([DataSourceRequest]DataSourceRequest request, FilterModel model)
        {
            ...
        }
Here is code from FilterModel.cs:
/// <summary>
        /// Start date of time interval
        /// </summary>
        public DateTime DateFrom { get; set; }
 
        /// <summary>
        /// Finish date of time interval
        /// </summary>
        public DateTime DateTo { get; set; }
 
        /// <summary>
        /// List of products
        /// </summary>
        public string[] Products { get; set; }
In MyController GetGridData method I have empty model with default values for dates and null for array.

However if I use simple ajax like following
$.ajax({
      url: 'MyController/GetGridData',
      data: $('#form').serializeArray(),
      type: 'POST'
    });
GetGridData method takes filled model.
I used Fiddler to see what is transfered during Read ajax method and simple ajax call:
Read ajax method:
0%5Bname%5D=FilterCriteria.DateFrom&0%5Bvalue%5D=8%2F6%2F2013+10%3A55+AM&1%5Bname%5D=FilterCriteria.DateTo&1%5Bvalue%5D=8%2F6%2F2013+11%3A55+AM&sort=&page=1&pageSize=15&group=&filter=
simple ajax:
FilterCriteria.DateFrom=8%2F6%2F2013+10%3A54+AM&FilterCriteria.DateTo=8%2F6%2F2013+11%3A54+AM

Probably because of this difference I cann't take filled model in controller action.

So, can someone, please, advice how can I get filled model in controller action for ajax Read datasource of the Grid using form serialization?
Atanas Korchev
Telerik team
commented on 08 Aug 2013, 06:45 AM

Hi,

How does the posted data looks like? You can find this by using the Network tab of your browser's developer tools. Most probably ASP.NET MVC default model binder cannot parse the data returned by jQuery serializeArray().

Regards,
Atanas Korchev
Telerik
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
ITO
Top achievements
Rank 1
commented on 22 Sep 2014, 05:51 PM

Hi, 

I have a similar question.
.Read(read => read.Action("action", "controller").Data("GetCommitteeSearchParam")) is not working in IE 10. In IE8 and chrome the same code is working fine without any issues. Once we upgraded to IE 10, it stopped working. The function "GetCommitteeSearchParam" is not reached, so parameters are not passed. Could you provide any alternate solution for this?

function GetCommitteeSearchParam()
{


    return {
        committeeName: $('#txtCommName').val(),
        committeeType: $('#CommitteeTypeList').val()
    };
}

@(Html.Kendo().Grid(Model)
        .Name("CommitteeGrid")
        .Columns(col =>
            {
                col.Bound(c => c.committeeView.CommitteeName).
                col.Bound(c => c.committeeView.CommitteeTypeValue).Width("250").Title("Committee Type");
                col.Bound(c => c.committeeView.CommitteeSize).Width("80");                   
            })
              .Pageable(pager=> pager
                .PreviousNext(false)
            )
             .Sortable()  
    
    .DataSource(dataSource => dataSource
      .Ajax()
          
        .Read(read => read.Action("action", "controller").Data("GetCommitteeSearchParam"))
        .PageSize(15)
        .ServerOperation(true)
        .Model(model => model.Id(c => c.CommitteeID))
        
        )
        
        )








Atanas Korchev
Telerik team
commented on 23 Sep 2014, 06:32 AM

Hello,

Unfortunately this is not a known issue and we cannot reproduce it locally. I recommend opening a support ticket and attaching a short sample project which reproduces that behavior. 

Regards,
Atanas Korchev
Telerik
 
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
 
reader
Top achievements
Rank 1
commented on 05 Feb 2015, 07:51 PM

how to include variables in additionalInfo? I tried below, it does not work. Thanks.

function additionalInfo() {
   var t = 'test';
    return {
        name: t,
        id: 2
    }
}
Geary
Top achievements
Rank 1
commented on 13 Aug 2015, 07:55 PM

Does this also work for Create, Update and Delete? !?!?!?
Geary
Top achievements
Rank 1
commented on 13 Aug 2015, 07:55 PM

Does this also work for Create, Update and Delete? !?!?!?
Dimiter Madjarov
Telerik team
commented on 14 Aug 2015, 07:21 AM

Hello Geary,

Yes, additional parameters could be passed the same way for the other CRUD operations.

Regards,
Dimiter Madjarov
Telerik
 
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
 
tam
Top achievements
Rank 1
commented on 04 Mar 2016, 12:30 AM

Hi Dimiter,

I have tried to pass parameters via the Data method but the data is not getting through when it's a variable or a value of an input element.

The code that is commented out does not work, but using the static values work. Can you help with this? Thank you

.Read(read => read.Action("GetWarehouse2", "Home").Data("getWHparameters"))

 

function getWHparameters() {            
            return {
                qtline: 1, //$("[name=whindex]").val(), //document.getElementById("whindex").value,
                vendor: 'Vendor' //$("[name=whvendor]").val() // document.getElementById("whvendor").value
            }
        } 

Dimiter Madjarov
Telerik team
commented on 07 Mar 2016, 01:04 PM

Hello tam,

I would recommend to debug the function and assure that the value of the input element is retrieved as expected.

Regards,
Dimiter Madjarov
Telerik
 
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
 
0
Gavin
Top achievements
Rank 1
answered on 05 Jun 2015, 01:00 PM

Hi,

How can I achieve this with a scheduler defined in javascript (i.e. not Razor) but still calling an MVC controller action?

 

Thanks,

Gavin

 

Dimiter Madjarov
Telerik team
commented on 08 Jun 2015, 07:12 AM

Hello Gavin,

The approach in this case would be the same - the transport.read.data configuration of the dataSource should be used in order to provide the additional data.

I hope this information helps, if further assistance is required, please open a separate thread in the Scheduler section or a support ticket.

Regards,
Dimiter Madjarov
Telerik
 
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
 
Gavin
Top achievements
Rank 1
commented on 09 Jun 2015, 08:01 AM

Thanks Dimiter!
0
Luis
Top achievements
Rank 1
answered on 24 Jun 2015, 11:01 PM

Hello

I am having a similar but very weird issue.

I am creating an editable grid in a view passing an integer model. I have configured edit, destroy and create actions. In every action I am passing back the integer model of the view to the controller. The Read, Update and Destroy actions are correctly passing this integer model. However, the Create action is not, even though it is defined in the same was as the others:

 

My Grid

@model int

@(Html.Kendo().Grid<MyGridModel>()
          .Name("MyGridModelGrid" + Model)
          .Columns(cols =>
          {
              cols.Bound(a => a.SomeProperty);
              cols.Bound(a => a.SomeListProperty).ClientTemplate("#=iterateOver(SomeListProperty)#").Title("Properties");
              cols.Command(command =>
             {
                 command.Edit();
                 command.Destroy();
             }).Width(172);
          })
          .ToolBar(toolbar => toolbar.Create())
          .Editable(editable => editable.Mode(GridEditMode.InLine))
          .DataSource(dataSource => dataSource
              .Ajax()
              .Model(m =>
              {
                  m.Id(model=>model.Id);
                  m.Field(model=>model.SomeProperty);
                  m.Field(model=>model.SomeListProperty).DefaultValue(new List<string>());
              })
            .Create(update => update.Action("AddModelFor", "MyController", new { area = "MyArea" , modelId= Model}))
            .Read(read => read.Action("ReadModelsFor", "MyController", new { area = "MyArea", modelId= Model }))
            .Update(update => update.Action("UpdateModelFor", "MyController", new { area = "MyArea", modelId= Model }))
            .Destroy(update => update.Action("RemoveModelFor", "MyController", new { area = "MyArea",modelId = Model }))
          )
    )

 

My MVC controller:

 

 public JsonResult ReadModelsFor([DataSourceRequest] DataSourceRequest request, int modelId)
        {
            //correctly receiving both parameters
        }

        [HttpPost]
         public ActionResult RemoveModelFor([DataSourceRequest]DataSourceRequest request, ServiceMapping serviceMapping, int modelId)
         {
                //correctly receiving the three parameters
         }

         [HttpPost]
         public ActionResult AddModelFor([DataSourceRequest]DataSourceRequest request, ServiceMapping serviceMapping, int modelId)
         {
             //THIS DOES NOT RECEIVE THE MODELID! 
         }

         [HttpPost]
         public ActionResult UpdateModelFor([DataSourceRequest]DataSourceRequest request, ServiceMapping serviceMapping, int  modelId)
         {
             //correctly receiving the three parameters
         }

Dimiter Madjarov
Telerik team
commented on 25 Jun 2015, 07:55 AM

Hello Luis,

The code seems correct, so we cannot state for sure what is causing the problem. I would suggest to open a support ticket for the issue and send us small runnable project, so we can see it in action.

Thanks for the understanding.

Regards,
Dimiter Madjarov
Telerik
 
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
 
Nasser
Top achievements
Rank 1
commented on 06 Aug 2015, 05:59 PM

Hi Luis,

If you solved the parameter issue for the Create method please tell me how.

I am facing exactly the same problem.

Kind Regards,

Luis
Top achievements
Rank 1
commented on 06 Aug 2015, 07:45 PM

Sure Ahmad

Inside my razor view I identified the method which was not sending correctly the missing property (In my case the id). So I added the following:

               .Create(create => create.Action("​MyMethod", "​MyController", new {area = "​MyArea", modelId = Model}).Data("customJSFunction"))

 

And inside my customJSFunction I just set the missing property that was not being sent to my controller:

 

customJSFunction(modelSent){

e.MissingProperty = "someValue" // can be substituted with any value

}

 

When your model is ​recieved to the controller, the MissingProperty will be set to "SomeValue"

I hope this helps/


 

Nasser
Top achievements
Rank 1
commented on 09 Aug 2015, 04:52 AM

Thank you Luis,

I also found another solution 

 .Create("VipProfile_Create", "VipProfiles", new { parentId = @ViewBag.PersonID })

The trick is to use a variable name (e.g. parentId) that is different from data source fields.

Hope this will save time for somebody.

Kind Regards

0
DHHS
Top achievements
Rank 1
answered on 09 Sep 2015, 08:17 PM

Hi Dimiter,

I have grid on the button click , which takes parameters from viewbag. It works fine when first time loads. when i click the button for the different record, it still takes the same parameter values of the first one.

I am reading the grid again on the button click. 

 

   <div class="container-fluid">
        <div class="row">
            <div class="col-xs-18 col-md-12">
                @(Html.Kendo().Grid<BHEBS.Areas.Budget.Models.ContractBudgetModel.contractBudgetServiceBUModel>()
        .Name("grid")
        .Columns(columns =>
        {
            columns.Bound(p => p.Id).Hidden(true);
            columns.Bound(p => p.CB_Id).Hidden(true);
            columns.Bound(p => p.Contractor_Id).Hidden(true);
            columns.Bound(p => p.Sd_Id).Hidden(true);
            columns.Bound(p => p.BUId);
            columns.Bound(p => p.BudgetDetailAmt).EditorTemplateName("Currency").Format("{0:c}");
            columns.ForeignKey(p => p.ProviderSpendPriority, (System.Collections.IEnumerable)ViewData["SpendPriority"], "Id", "SpendPriority");
            columns.Bound(p => p.ContractBudgetAmount).Format("{0:c}");
            columns.Bound(p => p.ContractSpendPriority);
            columns.Bound(p => p.MasterBudgetAmount).Format("{0:c}");
            columns.Command(command =>
            {
                command.Edit().HtmlAttributes(new { @class = "btn-primary" });
                command.Destroy().HtmlAttributes(new { @class = "btn-primary" });
            }).Width(300);
            //  columns.Command(command => command.Custom("Remove").SendDataKeys(true).Click("deleteClick").HtmlAttributes(new { @class = "k-button k-button-icontext k-grid-add k-primary" }));
        })
                        //.Events(e => e.DataBound("onDataBound"))
        .Pageable(pageable => pageable.Refresh(true).PageSizes(true).ButtonCount(5))
        .Sortable()
        .Scrollable()
        .Filterable()
        .Selectable()
        .Resizable(resize => resize.Columns(true))
        .HtmlAttributes(new { style = "height:450px;" })
        .DataSource(dataSource => dataSource.Ajax().PageSize(10).Read(read => read.Action("ContractBudgetServiceBU_Read", "ContractBudget", new { contractorId = ViewBag.contractorId, contractId = @Html.Raw(Json.Encode(Model.Id)), serviceDetailId = ViewBag.serviceDetailId }))
        .Model(model =>
        {
            model.Id(p => p.Id); model.Field(p => p.Id).Editable(false); model.Field(p => p.CB_Id).Editable(false); model.Field(p => p.Contractor_Id).Editable(false);
            model.Field(p => p.Sd_Id).Editable(false); model.Field(p => p.ContractBudgetAmount).Editable(false); model.Field(p => p.ContractSpendPriority).Editable(false); model.Field(p => p.MasterBudgetAmount).Editable(false);
        })
        .Update(update => update.Action("Update_ContractBudgetServiceBU", "ContractBudget")).Destroy(destroy => destroy.Action("Destroy_ContractBudgetServiceBU", "ContractBudget"))
                       .Events(e => e.Error(@<text>
            function(args) {
            var gridName = 'grid';
            errorGrid(args, gridName);  }  </text>)) ))
            </div>
        </div>
    </div>
 
 
 
@(Html.Kendo().Window()
    .Name("window")
    .Title("Assign Business Units")
    .Content(@<text><div class="container-fluid">
            <div class="row">
                <div class="col-xs-18 col-md-12">
                    @(Html.Kendo().Grid<BHEBS.Areas.Budget.Models.ContractBudgetModel.contractBudgetBUModel>()
        .Name("grid1")
        .Columns(columns =>
        {
            columns.Template(x => { }).HtmlAttributes(new { @class = "chkbox" }).ClientTemplate("<input type='checkbox' class='checkbox' id = 'chk' />");
            columns.Bound(p => p.Id);
            columns.Bound(p => p.BusinessUnit);
            columns.Bound(p => p.Description);
            columns.Bound(p => p.ServiceType);
            columns.Bound(p => p.ContractBUAmt).Format("{0:c}");          
        })
        .Pageable(pageable => pageable.Refresh(true).PageSizes(true).ButtonCount(5))
        .Sortable()
        .Scrollable()
        .Filterable()
        .Selectable()
        .Resizable(resize => resize.Columns(true))
        .HtmlAttributes(new { style = "height:450px;" })
// this is the grid am talking about. These take parameters.
        .DataSource(dataSource => dataSource.Ajax().PageSize(10).Read(read => read.Action("GetAllContractBudget_Read", "ContractBudget", new { contractId = @Html.Raw(Json.Encode(Model.Id)), contractorId = @ViewBag.ContractorId, serviceDetailId = @ViewBag.ContractDetailBudgetService.ServiceDetailId })).Model(model => model.Id(p => p.Id))))
                    <button class="k-button close-button k-primary" style="bottom: 10px; ">Cancel</button>
                    <button class="k-button k-primary" id="showSelection" style="bottom: 10px; ">Assign</button>
                </div>
            </div>
        </div></text>)
                                                    .Draggable()
                                                    .Resizable()
                                                    .Width(1000)
                                                    .Modal(true)
                                                    .Visible(false))
 
    $(document).ready(function(){
        var serviceId =  '@(ViewBag.serviceDetailId)';
        alert(serviceId);
        $("#kendowindow").click(function(){
            $("#window").data("kendoWindow").center().open();
            $("#grid1").css("margin-right","30px");
// this is how am refreshing the grid. This works fine for the first time for the first record. when i go back to another page and come back with some other parameter values, i can see the viewbag values or proper, but when i click the button read method has first time parameters.
          $('#grid1').data().kendoGrid.dataSource.read();
        });
});

DHHS
Top achievements
Rank 1
commented on 09 Sep 2015, 08:57 PM

Can you please tell me how to refresh the grid with different parameter values on button click.  I am sending parameters like this while initial load .

.DataSource(dataSource => dataSource.Ajax().PageSize(10)
.Read(read => read.Action("GetAllContractBudget_Read", "ContractBudget",
new { contractId = @Html.Raw(Json.Encode(Model.Id)),
contractorId = @ViewBag.ContractorId,
serviceDetailId = @ViewBag.ContractDetailBudgetService.ServiceDetailId }))
.Model(model => model.Id(p => p.Id))))

 

 

Thanks,

Veena

Dimiter Madjarov
Telerik team
commented on 10 Sep 2015, 08:42 AM

Hello DHHS,

When the additional parameters are added in the Grid configuration as route values, they are attached to the read action URL.
E.g.

Grid/Orders_Read?contractId=1
so they will be send each time.

Another approach that you could try would be to omit them and use the Data() method to define a JavaScript function that will return the additional data for the request. This way you could include the custom logic for determining what values to be sent inside this function.
E.g.
.Read(read => read.Action("Orders_Read", "Grid").Data("getAdditionalData"))
function getAdditionalData(e) {
    return {
        contractId: 1
    };
}

Regards,
Dimiter Madjarov
Telerik
 
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
 
0
Shashank
Top achievements
Rank 1
answered on 31 May 2017, 09:02 AM

Hello dimiter,

Is it possible to pass DataSourceRequest class properties from KendoGrid, like this:

Public ActionResult Index(string filterValue, int? currentPage = 1, string Sort = "FirstName", string Sortdir = "ASC", int RowPerPage = 10, string PageRefresh = "False")

{

//my custom code

}

 

now from kendo call Can I do this:

.Read(read => read.Action("Orders_Read", "Grid").Data("getAdditionalData"))
function getAdditionalData(e) {
    return {
        PageNo: 1, 
PageSize: ?what how value?, Filters: ?what how value?, Groups:?what how value?

    };
}

 

?what how value? : how these values will get fetched?????

 

I want to pass it from kendo grid rather than doing it by own using DataSourceRequest as shown below:

 public ActionResult readPagingData([Kendo.Mvc.UI.DataSourceRequest] Kendo.Mvc.UI.DataSourceRequest request)
        {

var result = new Kendo.Mvc.UI.DataSourceResult()
            {
                Data = GetData(),
                Total = TotalRe
            };
            return Json(result, JsonRequestBehavior.AllowGet);

}

Stefan
Telerik team
commented on 02 Jun 2017, 06:22 AM

Hello Shashank,

I noticed that my colleague provided an answer to the same question in the support ticket.

I will share it with the Kendo UI community if anybody has a similar question:


"Note that all parameters are sent to your getAdditionalData function in the e argument. So, based on this, you can generate your data parameters:"

function getAdditionalData(e) {
    return {
        PageNo: e.page, PageSize: e.pageSize, Filters: JSON.stringify(e.filters), Groups:  JSON.stringify(e.group)
    };
}

"You may need to modify how the group and filter expression are sent, based on what format you expect in the controller method."


Regards,
Stefan
Progress Telerik
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.
0
Thomas
Top achievements
Rank 1
answered on 10 Aug 2017, 04:50 PM

Hi, 

is there a way to bind this additional data function

.Read(read => read.Action("Products_Read""Grid").Data("additionalInfo"))

 

via javascript?

So far I have tried it like this:

headerSchnellsuche.bind("data", function () {
 console.log("Set data");
});

 

but without success

Stefan
Telerik team
commented on 14 Aug 2017, 11:12 AM

Hello Thomas,

The additional data function is passed to the Data configuration using the function name, in the provided example this is additionalInfo. The additionalInfo function(which is a custom function that has to be created) will be called and the desired logic can be executed there.

.Read(read => read.Action("Products_Read", "Grid").Data("additionalInfo"))
 
<script>
function additionalInfo(){
console.log("The additionalInfo function is called.")
}
</script>

Let me know if you need additional assistance on this matter.

Regards,
Stefan
Progress Telerik
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 visualization (charts) and form elements.
Thomas
Top achievements
Rank 1
commented on 15 Aug 2017, 09:35 PM

Hi Stefan,

as I showed in my post I know how to use the function when setting it inside razor (like you did). I am asking if its possible to set the function dynamically with javascript 

Stefan
Telerik team
commented on 17 Aug 2017, 09:03 AM

Hello Thomas,

The function which will be responsible for the data can be changed dynamically if a new dataSource with a new function is passed to the Grid using its setDataSource method:

http://docs.telerik.com/kendo-ui/api/javascript/ui/grid#methods-setDataSource

Please have in mind that the code snippet which was provided for binding is supported only for events.

Regards,
Stefan
Progress Telerik
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 visualization (charts) and form elements.
0
BitShift
Top achievements
Rank 1
Veteran
answered on 09 Oct 2017, 08:31 PM
I know this is an old post, but is there anyway to make the additional parameters available in a custom object?  In other words, the parameters would be a DataSourceRequest and a custom object of some type that is used to pass in a JSON formatted object?
Stefan
Telerik team
commented on 11 Oct 2017, 10:46 AM

Hello,  Randal,

Currently, a custom object can be passed to the server using the mentioned Data function:

.Read(read => read.Action("Products_Read""Grid").Data("additionalInfo"))

Copy Code
function additionalInfo() {
    return {
        name: "test",
        id: 2
    }
}
Copy Code
public ActionResult Products_Read([DataSourceRequest] DataSourceRequest request, string name, int id) {...}


If the scenario is more specific, please provide more details and I will gladly assist.

Regards,
Stefan
Progress Telerik
Try our brand new, jQuery-free Angular components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.
0
Anoj
Top achievements
Rank 1
answered on 19 Aug 2019, 04:01 PM

Thanks, Passed the data using object route values/1st method. I prefer using JavaScript way to pass the data, But that doesn't work for me. 

-Anoj

Alex Hajigeorgieva
Telerik team
commented on 21 Aug 2019, 10:50 AM

Hi, Anoj,

You could use the AutoBind(false) for the grid and then the data source read() method. This will allow you to use JavaScript and pass additional parameters as an object parameter:

@(Html.Kendo().Grid<OrderViewModel>()
    .AutoBind(false)
    .Name("grid"
   /* other configuration */
)
 $(document).ready(function () {
    var grid = $("#grid").data("kendoGrid");
    grid.dataSource.read({
       name: "test",
       id: 2
    });
});


Kind Regards,
Alex Hajigeorgieva
Progress Telerik
Get quickly onboarded and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers. Learn More.
0
freeTheCode
Top achievements
Rank 1
answered on 27 Feb 2020, 08:08 PM

I know this post is old but I have a question on the use of the javascript Data function. Is it possible to pass a variable to it. It seems that this is not possible and causes issues with events not firing. What am I missing?

 

Read(read => read.Action("Products_Read", "Grid").Data("additionalInfo(" + myparameter + ")" ))

 

 

function additionalInfo(parameter) {
    return {
        name: "test",
        id: parameter
    }
}
Alex Hajigeorgieva
Telerik team
commented on 02 Mar 2020, 03:04 PM

Hi,

The provided code snippets work well in my test and are successfully sent along with the rest of the data:

@{ 
    var myparameter = 12;
}
   

However, if you provide some more details about the desired outcome, we might be able to see what could be the cause for unexpected behaviour in your project.

Kind Regards,
Alex Hajigeorgieva
Progress Telerik

Get quickly onboarded and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers. Learn More.
0
Kiran
Top achievements
Rank 1
Veteran
Iron
answered on 18 Jun 2020, 05:19 PM

Hi,

 

I want to use this way to pass the dynamic values, my javascript function in separate JS file.

 

.Read(read => read.Action("Products_Read", "Grid").Data("additionalInfo("+ Model.DynamicID +")"))

Let me know any option like that?

Peter Milchev
Telerik team
commented on 22 Jun 2020, 12:11 PM

Hello Kiran,

The code you have provided works perfectly as long as Model.DynamicID is a number. Then, the function translated to pure JavaScript will look as:

additionalInfo(42)

If Model.DynamicID is a string, then the same function will be translated to additionalInfo(someID). That means the JavaScript will look for a global someID variable and will throw an error if there is no such variable. 

In such a case, you would need to add quotes around the value so that you pass it as a string parameter.

.Read(read => read.Action("Products_Read", "Grid").Data("additionalInfo(' "+ Model.DynamicID +" ')"))

Regarding the declaration of the additionalInfo function, it does not really matter if it is declared on the page or in an external file as long as it is loaded by the time the Grid is initialized and calls it.

Regards,
Peter Milchev
Progress Telerik

Progress is here for your business, like always. Read more about the measures we are taking to ensure business continuity and help fight the COVID-19 pandemic.
Our thoughts here at Progress are with those affected by the outbreak.
0
Zoran
Top achievements
Rank 1
Veteran
answered on 12 Aug 2020, 11:00 AM

I have the populated model in the View below which I want to send to the Upload_Read method in the Upload Controller.
I tried sending the model as a parameter but it seems it's not possible to do it this way.

What would be the best way to send the Model to the Upload_Read method so that I can use it for the Kendo grid?

.Read(read => read.Action("Upload_Read", "Upload", Model))
Nikolay
Telerik team
commented on 14 Aug 2020, 09:24 AM

Hello Zoran,

Additional parameters can be sent to the remote service via the .Data() configuration, for example:

.DataSource(ds => ds
                    .Read(read => read.Action("GetCustomerWarrantyDates", "Customer").Data("CustomerDatePeriod"))
                )
...
function CustomerDatePeriod() {
            model = {  // build the model }
        return model
    }

and pass those model parameters to the Action method:

        public ActionResult GetCustomerWarrantyDates([DataSourceRequest] DataSourceRequest request, SalesOrdersParameters parameters)
        {
        }

Let me know if you have any questions.

Regards,
Nikolay
Progress Telerik

0
Dave Wolf
Top achievements
Rank 1
Iron
answered on 14 Jun 2022, 10:21 PM
Can this work with dynamic JavaScript parameters?  This JavaScript Data function only seems to get called on initialization of the combobox.  We have a parameter that changes after the page is loaded.  What's the best way to have the datasource include the new value of the parameter on the next request to the server?
Dave Wolf
Top achievements
Rank 1
Iron
commented on 14 Jun 2022, 11:33 PM

Please disregard, I had something configured incorrectly.
Tags
Grid
Asked by
Nirav
Top achievements
Rank 1
Answers by
Dimiter Madjarov
Telerik team
Gavin
Top achievements
Rank 1
Luis
Top achievements
Rank 1
DHHS
Top achievements
Rank 1
Shashank
Top achievements
Rank 1
Thomas
Top achievements
Rank 1
BitShift
Top achievements
Rank 1
Veteran
Anoj
Top achievements
Rank 1
freeTheCode
Top achievements
Rank 1
Kiran
Top achievements
Rank 1
Veteran
Iron
Zoran
Top achievements
Rank 1
Veteran
Dave Wolf
Top achievements
Rank 1
Iron
Share this question
or