0

I'm building an app in C# (which is a little rusty) and I'm using an AJAX call to return some data from my database. I want to add some filtering to this by passing an object to the controller.

I've got it working when just one filter is used but I'm struggling when it comes to multiple filters. How do I set this up so I can check to see if that filter is being used and then filter the database on it?

This is my current code:

JS:

dataObj = new Object;
if (FormData) {
   $.each(FormData, function (index, item) {
       dataObj[item.name] = item.value;                  
   });
};
$.ajax({
    url: '@Url.Action("GetCompanies")',
    data: dataObj,
    type: 'GET',
    dataType: 'json',
    success: function (result) {
        //Do stuff with data
    }
});

Controller:

public JsonResult GetCompanies(SearchFilter SearchFilters)
{
    if (!String.IsNullOrEmpty(SearchFilters.CustomerType) && SearchFilters.CustomerType != "All")
    {
        var data = _db.Customers.Where(a => a.Type.Contains(SearchFilters.CustomerType)).ToList();
        var jsonData = Json(data, JsonRequestBehavior.AllowGet);
        return jsonData;
    }
    else
    {
        var data = _db.Customers.ToList();
        var jsonData = Json(data, JsonRequestBehavior.AllowGet);
        return jsonData;
    }
}

Thanks in advance!

  • Make sure your `dataObj` contains data [in a certain format](https://stackoverflow.com/a/37238682/11683) that the model binder understands as a list. – GSerg Oct 21 '18 at 18:19
  • Thanks @GSerg - the 'dataObj' is fine, it binds to the model perfectly - i guess my question is if the users puts two search string in rather than one (for example: CustomerType and CustomerName) then how do I handle this in the where clause? Or how do i build the query dynamically based on the data in the model? – Ian Hill Oct 22 '18 at 11:25
  • Change `GetCompanies` to `GetCompanies(List SearchFilters)` and make sure your `dataObj` contains data [in a certain format](https://stackoverflow.com/a/37238682/11683) that the model binder understands as a list. – GSerg Oct 22 '18 at 11:28
  • That's not the problem, the ajax call and model binds perfectly. I'm having trouble querying the database with multiple (and optional) parameters. I've looked into IQueryable but my knowledge there is very limited. – Ian Hill Oct 22 '18 at 12:37
  • 1
    Have a loop over the filters list and [add another `Where`](https://stackoverflow.com/a/8791596/11683) on each iteration. – GSerg Oct 22 '18 at 12:41
  • Doh! I've been trying to build it in one querystring! Thanks :) – Ian Hill Oct 22 '18 at 13:48
  • Possible duplicate of [Multiple WHERE Clauses with LINQ extension methods](https://stackoverflow.com/questions/8791540/multiple-where-clauses-with-linq-extension-methods) – GSerg Oct 22 '18 at 14:16

0 Answers0