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

Code Sample: Sending additional filters with Ajax Binding

2 Answers 353 Views
Grid
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Michael Maluck
Top achievements
Rank 2
Michael Maluck asked on 19 Mar 2011, 12:52 PM
Done with Telerik Extensions for ASP.NET MVC Q1 2011 (03/15/2011)

This sample shows how to send additional filters to you server side data query method. The example sends back two additional filter value. The first one is a country name that can be chosen from a ComboBox. The second one is a search text that will filter data be in multiple columns. In this case it searches for the leading numbers of an Order ID and for a Shipping Contact. If the search text will match in any of the columns the according record will be displayed. You can still use built-in grid filters, sorting and paging.

The key is to sending additional values to the server is modifying the ajax selectUrl of the grid. This is done in a OnDataBinding client event handler. In the event handler the values of the Country ComboBox and the Search Text InputBox is fetched, a parameter string is created and attached to the action url. The resulting url is finally assigned to the axaj selectUrl of the grid.

In the controller the two additional fields can be added to the model for automatically assigning its values. The data source is filtered by our custom filters and then passed to the GridModel.

[View]

<%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage<Telerik.Web.Mvc.Examples.AjaxFilterBindingModel>" %>
<asp:Content ContentPlaceHolderID="MainContent" runat="server">
 
<div>
Select Country:
<%= Html.Telerik().ComboBox()
        .Name("Country")
        .BindTo(new SelectList(Model.Countries))
%>
</div>
<div>
Enter start of Order ID or part of Contact Name:
<%= Html.TextBoxFor(model => model.SearchText) %>
</div>
<div>
<a href="javascript:filterGridData();">Filter grid data with Ajax</a>
</div>
<%= Html.Telerik().Grid<Order>()
        .Name("Grid")
        .ClientEvents(events => events.OnDataBinding("onDataBinding"))
        .Columns(columns =>
        {
            columns.Bound(o => o.OrderID).Width(100);
            columns.Bound(o => o.Customer.ContactName).Width(200);
            columns.Bound(o => o.ShipAddress);
            columns.Bound(o => o.OrderDate).Format("{0:MM/dd/yyyy}").Width(120);
        })
        .DataBinding(dataBinding => dataBinding.Ajax().Select("_AjaxBinding", "Grid"))
        .Pageable()
        .Sortable()
        .Scrollable()
        .Groupable()
        .Filterable()
%>
<script type="text/javascript">
    function onDataBinding(e) {
        var country = $('#Country').val();
        var searchText = $('#SearchText').val();
        var params = { Country: country, SearchText: searchText };
        var paramsStr = $.param(params);
        var selectUrl = "<%= @Url.Action("_AjaxFilterBinding", "Grid") %>" + "?" + paramsStr;
        var grid = $('#Grid').data('tGrid');
        grid.ajax.selectUrl = selectUrl;
    }
 
    function filterGridData() {
        var grid = $('#Grid').data('tGrid');
        grid.ajaxRequest();
    }
</script>
</asp:Content>

[Controller]

namespace Telerik.Web.Mvc.Examples
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Mvc;
    using Models;
 
    public partial class GridController : Controller
    {
        public ActionResult AjaxFilterBinding(AjaxFilterBindingModel model)
        {
            var countries = (from customer in GetCustomers()
                             orderby customer.Country
                             select customer.Country).Distinct();
            model.Countries = countries.ToList();
            return View(model);
        }
 
        [GridAction]
        public ActionResult _AjaxFilterBinding(AjaxFilterBindingModel model)
        {
            var qry = GetOrders().AsQueryable();
            if (!string.IsNullOrEmpty(model.Country))
            {
                qry = qry.Where(order => order.Customer.Country == model.Country);
            }
            if (!string.IsNullOrEmpty(model.SearchText))
            {
                qry = qry.Where(order =>
                                order.OrderID.ToString().StartsWith(model.SearchText) ||
                                order.Customer.ContactName.Contains(model.SearchText));
            }
            var data = qry.ToList();
            return View(new GridModel<Order>
                            {
                                Data = data
                            });
        }
    }
 
    public class AjaxFilterBindingModel
    {
        public IEnumerable<string> Countries { get; set; }
        public string Country { get; set; }
        public string SearchText { get; set; }
    }
}


@Telerik: Feel free to include this code/description in your samples or do with it whatever you like. I implemented it in your sample project so it should run instantly. I used the same data as in the Ajax Binding sample to make it easier for people to see the differences. Maybe the View needs some UI polishing.

Edit: I also attached the source files but with a small typo. Just don't know how to replace already attached files.

Best wishes,
Michael

2 Answers, 1 is accepted

Sort by
0
Atanas Korchev
Telerik team
answered on 20 Mar 2011, 09:45 AM
Hello Michael Maluck,

 You can easily add additional parameters by using the data argument of the ondatabinding event:

   e.data = { foo: 1, bar: 2};

Probably this would be easier to implement.

Also you may consider submitting a code library entry.

Regards,
Atanas Korchev
the Telerik team
0
frederic rybkowski
Top achievements
Rank 1
answered on 21 Mar 2011, 09:46 AM
Hello,
Why don't you use args in Grid.Rebind()  (see Grid.js) ?


Tags
Grid
Asked by
Michael Maluck
Top achievements
Rank 2
Answers by
Atanas Korchev
Telerik team
frederic rybkowski
Top achievements
Rank 1
Share this question
or