KendoUI Grid Ajax Binding Parameters For Select

15,866

Solution 1

Nicholas answer could work if your requirements can be solved with the built in filtering. But if your requirements can be solved with the built filtering why do you want to create a custom search form?

So I suppose you have a reason to do the search manually so here is how we've done it in our project (so maybe there is more easier way but still this worked for us):

The controller action is fine:

public ActionResult _Search([DataSourceRequest]DataSourceRequest request, 
                            CustomerSearchModel customerSearchModel)
{
    return Json(DataService.GetCustomers2(customerSearchModel)
               .ToDataSourceResult(request));
}

Next step: you need a JavaScript function which collects the data from the search form (the property names of the JS object should match the property names of your CustomerSearchModel) :

function getAdditionalData() {
    // Reserved property names
    // used by DataSourceRequest: sort, page, pageSize, group, filter
    return {
        FirstName: $("#FirstName").val(),
        LastName: $("#LastName").val(),
        //...
    };
}

Then you can configure this function to be called on each read:

.DataSource(dataSource => dataSource
        .Ajax()
        .Read(read => read.Action("_Search", "Customer")
                          .Data("getAdditionalData"))
    )

Finally in your button click you just need to refresh the grid with:

$('#Grid').data('kendoGrid').dataSource.fetch();

Solution 2

You can set the filters on the grid by calling filter on the grid's data source.

So in your button's onclick handler function, put something like this:

var $Grid = $('#Grid').data('kendoGrid');

$Grid.dataSource.filter([
  { field: 'FirstName', operator: 'eq', value: $('#firstName').val() },
  { field: 'LastName', operator: 'eq', value: $('#lastName').val() }
]);

Here's a link to the Kendo docs: DataSource.filter

Solution 3

Refer Pass Additional Data to the Action Method

To pass additional parameters to the action use the Data method. Provide the name of a JavaScript function which will return a JavaScript object with the additional data:

A working Search example listed below:

Important: type="button" for the button; And AutoBind(false) for Grid; otherwise, it won’t work

VIEW

@model  IEnumerable<KendoUIMvcSample.Models.Sample>
@{
    ViewBag.Title = "Index";
}


<script type="text/javascript">


    function getAdditionalData()
    {
        return {
            FirstName: 'A',
            LastName: 'B',
        };
    }

    $(document).ready(function ()
    {
        $('#Submit1').click(function ()
        {
            alert('Button Clicked');
            //Refresh the grid
            $('#ssgrid222').data('kendoGrid').dataSource.fetch();
        });

    });

</script>

<h2>Index</h2>
@using (Html.BeginForm())
{ 

    @(Html.Kendo().Grid<KendoUIMvcSample.Models.Sample>()    
    .Name("ssgrid222")
    .Columns(columns => {
        columns.Bound(p => p.SampleDescription).Filterable(false).Width(100);
        columns.Bound(p => p.SampleCode).Filterable(false).Width(100);
        columns.Bound(p => p.SampleItems).Filterable(false).Width(100);
    })
    .AutoBind(false)
    .Pageable()
    .Sortable()
    .Scrollable()
    .Filterable()
    .HtmlAttributes(new { style = "height:430px;" })
    .DataSource(dataSource => dataSource
        .Ajax()
        .PageSize(20)
        .Read(read => read.Action("Orders_Read", "Sample")
        .Data("getAdditionalData"))
     )
  )

 <input id="Submit1" type="button" value="SubmitValue" />

}

Controller

namespace KendoUIMvcSample.Controllers
{
    public class SampleController : Controller
    {
        public ActionResult Index()
        {
            SampleModel AddSample = new SampleModel();
            Sample s1 = new Sample();
            return View(GetSamples());
        }
        public static IEnumerable<Sample> GetSamples()
        {
            List<Sample> sampleAdd = new List<Sample>();
            Sample s12 = new Sample();
            s12.SampleCode = "123se";
            s12.SampleDescription = "GOOD";
            s12.SampleItems = "newone";
            Sample s2 = new Sample();
            s2.SampleCode = "234se";
            s2.SampleDescription = "Average";
            s2.SampleItems = "oldone";
            sampleAdd.Add(s12);
            sampleAdd.Add(s2);
            return sampleAdd;
        }
        public ActionResult Orders_Read([DataSourceRequest]DataSourceRequest request, CustomerSearchModel customerSearchModel)
        {
            string firstParam = customerSearchModel.FirstName;
            return Json(GetOrders().ToDataSourceResult(request));
        }
        private static IEnumerable<Sample> GetOrders()
        {
            return GetSamples();
        }
    }
    public class CustomerSearchModel
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

Model

namespace KendoUIMvcSample.Models
{
    public class SampleModel
    {
        public List<Sample> samples;
    }
    public class Sample
    {
        public string SampleDescription { get; set; }
        public string SampleCode { get; set; }
        public string SampleItems { get; set; }
    }
}
Share:
15,866
RSolberg
Author by

RSolberg

@russsolberg http://rsolberg.com

Updated on June 27, 2022

Comments

  • RSolberg
    RSolberg almost 2 years

    I have a basic KendoUI Grid for my ASP.NET MVC app which uses ajax binding for the read. I'd like to enhance this so that a Form above the grid is used to help select data that should be displayed in the grid. This is a standard search form with basic fields like First Name, Last Name, Date of Birth, Customer Source, etc. with a search button. When the search button is pressed, I want to force the grid to go get the data that meets the criteria from the controller by passing in the Search Model with the fields I referenced above.

    The search form is contained within the _CustomerSearch partial view.

    I've implemented this sort of thing before with the Telerik MVC extensions by tapping into the OnDataBinding client event and updating the parameter values there and then manually making the Ajax call to get the data. It doesn't appear KendoUI will operate this same way.

    View

    @Html.Partial("_CustomerSearch", Model)
    <hr>
    @(Html.Kendo().Grid<ViewModels.CustomerModel>()    
        .Name("Grid")
        .Columns(columns =>
        {
            columns.Bound(p => p.Id).Hidden(true);
            columns.Bound(p => p.FirstName);
            columns.Bound(p => p.LastName);
            columns.Bound(p => p.DateOfBirth).Format("{0:MM/dd/yyyy}");
            columns.Bound(p => p.IsActive);
        })
        .Scrollable()
        .Filterable()
        .Sortable()
        .DataSource(dataSource => dataSource
            .Ajax()
            .Read(read => read.Action("_Search", "Customer"))
        )
    )
    

    Controller

    public ActionResult _Search([DataSourceRequest]DataSourceRequest request)
    {
        return Json(DataService.GetCustomers2().ToDataSourceResult(request));
    }
    

    I envision the controller looking something like this, but can't find any examples of anything being implemented this way, which is what I need help with.

    public ActionResult _Search([DataSourceRequest]DataSourceRequest request, CustomerSearchModel customerSearchModel)
    {
        return Json(DataService.GetCustomers2(customerSearchModel)
                   .ToDataSourceResult(request));
    }
    
  • RSolberg
    RSolberg about 11 years
    I need to filter at the server level and will be filtering on fields that are not displayed in the grid.
  • RSolberg
    RSolberg about 11 years
    I'm filtering my data on more fields than what I'm going to show in the grid. This is a master global search for customer data.
  • nemesv
    nemesv about 11 years
    I don't follow your comment... With the .Data("getAdditionalData") you can return any extra data to the server side it doesn't need to related to the grid at all... I've just used FirstName and LastName as an example.
  • RSolberg
    RSolberg about 11 years
    I was answering your initial statement of not sure why I wasn't using the built in... This looks promising. I'll take a look in a bit.
  • RSolberg
    RSolberg about 11 years
    Had to make a little syntax change for this to fly, but it's working like a charm! Thanks!!!
  • RSolberg
    RSolberg about 11 years
    Thanks for leaving this though... I'm going to reference this in other areas of my dev...
  • LCJ
    LCJ almost 11 years
    Thanks. Do you have any other references where this approach is used eitehr in Kendo UI site or anywhere else?
  • nemesv
    nemesv almost 11 years
    @Lijo I don't know about any written reference. We have figured out this approach on our internal projects based on the documentation.
  • LCJ
    LCJ almost 11 years
    @nemesv Thanks. I have posted an answer with a reference for this approach from Kendo site.
  • digawp
    digawp almost 9 years
    Why is the AutoBind(False) important? (Sorry I know this is an old question but I want to know why)
  • digawp
    digawp almost 9 years
    It is possible to filter fields not displayed in the grid using this method. However, it is NOT possible to filter fields NOT in the model you provide to the grid. Sorry I know this is an old thread but people referring to this in the future will need to know