KendoUI Grid Ajax Binding Parameters For Select

瘦欲@ 提交于 2019-12-20 20:32:28

问题


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));
}

回答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();



回答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




回答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; }
    }
}


来源:https://stackoverflow.com/questions/15667418/kendoui-grid-ajax-binding-parameters-for-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!