Autocomplete Server Filtering and WebApi2 Controller

2 posts, 0 answers
  1. Ricard Bertran Vall
    Ricard Bertran Vall avatar
    18 posts
    Member since:
    Sep 2009

    Posted 22 Sep 2016 Link to this post

    For those who're wondering how to catch KendoUI autocomplete filter on server side webapi2 controller without having to deal with filter.filters[0] query string prarameters.

    This is how I've solved it:

    JS:

    $("#values").kendoAutoComplete({
        minLength: 3,
        enforceMinLength: true,
        dataTextField: "value",
        dataValueField: "id",
        dataSource: {
            type: "json",
            severFiltering: true,
            serverPaging: true,
            transport: {
                read: "/api/values",
                parameterMap: function (data, type) {
                    return { filter: $('#values').val() };
                }
            }
        },
        filtering: function (e) {
            if (!e.filter.value) {
                e.preventDefault();
            }
        }
    });

     

    The trick here is to use  parameterMap to change request url.

     

    WebApi2:

    public class ValuesController : ApiController
    {
        // GET api/values
        [HttpGet]
        [Route("api/values", Name = "r2", Order = 2)]
        public IEnumerable<ValueModel> Get()
        {
            //var filters = new AutoCompleteFilters(Request.GetQueryNameValuePairs());
            return new List<ValueModel>() {
                new ValueModel() { id = 1, value = "item 1" },
                new ValueModel() { id = 2, value = "item 2" },
                new ValueModel() { id = 3, value = "item 3" },
            };
        }
        //GET api/values?filter=item
        //GET api/values/ite
        [HttpGet]
        [Route("api/values/{filter?}", Name = "r1", Order = 1)]
        public IEnumerable<ValueModel> Get(string filter)
        {
            return new List<ValueModel>() {
                new ValueModel() { id=1, value="item 1" },
                new ValueModel() { id=2, value="item 2" },
                new ValueModel() { id=3, value="item 3" },
            }.Where(m => m.value.StartsWith(filter, StringComparison.CurrentCultureIgnoreCase));
        }
    }

    The trick on WebApi2 is to use "named" Route attributes with optional {filter?} parameter

     

    This solution allows either :

    http://localhost:11989/api/values?filter=item

    or

    http://localhost:11989/api/values/ite

    What is cool in case your api is exposed to third-party applications.

    Happy coding!

     

     

  2. Lawrence
    Lawrence avatar
    14 posts
    Member since:
    Jul 2013

    Posted 23 Jun in reply to Ricard Bertran Vall Link to this post

    Excellent example.  Thank you sharing!!
Back to Top