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

Error when using filter array for grid searching

2 Answers 478 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Tom
Top achievements
Rank 1
Tom asked on 19 Sep 2018, 10:59 PM

I've got a grid set up as follows, where I'm trying to implement a basic multi-column search with an array of filters:

@(Html.Kendo().Grid<OpenPurchaseOrder>()
          .Name("grid")
          .DataSource(dataSource =>
            dataSource.Ajax()
              .Read(read => read.Action("OpenPurchaseOrders_Read", "GoodsIn"))
          )
    .ToolBar(toolbar =>
    {
      toolbar.Template(@<text>
                         <div class="toolbar">
 
                           <div class="row">
                             <div class="col-md-4">
                               <div class="input-group">
                                 <span class="input-group-addon"><span class="glyphicon glyphicon-search" aria-hidden="true"></span></span>
                                 <input type="text" class="form-control" id='FieldFilter' placeholder="Search for...">
                                 <span class="input-group-btn">
                                   <button class="btn btn-default" type="button"><span class="glyphicon glyphicon-refresh" aria-hidden="true"></span></button>
                                 </span>
                               </div>
                             </div>
                           </div>
                         </div>
                        </text>);
    })
     
    .Pageable()
              .Filterable()
              .Sortable()
              .Navigatable()
              .Columns(columns =>
              {
                var colHeadingStyle = "white-space: normal; vertical-align: top;";
 
                columns.Bound(docType => docType.PurchaseId)
                  .HeaderHtmlAttributes(new { style = colHeadingStyle });
                columns.Bound(docType => docType.ContactName)
                  .HeaderHtmlAttributes(new { style = colHeadingStyle });
                columns.Bound(docType => docType.PoType)
                  .HeaderHtmlAttributes(new { style = colHeadingStyle });
                columns.Bound(docType => docType.PoDate)
                  .HeaderHtmlAttributes(new { style = colHeadingStyle }).Format("{0:dd MMM yyyy}");
          //columns.Command(commands =>
          //{
          //  commands.Select();
          //}).Title("").Width(180);
          columns.Bound(p => p.PurchaseId).ClientTemplate(
                  "<a class='btn  btn-default' href='" +
                  Url.Action("Create", "GoodsIn") +
                  "?PurchaseId=#= PurchaseId #'" +
                  ">Receive</a>"
                  ).Title("").Width(80).Filterable(false);
              }))

 

<script type="text/javascript">
  $(document).ready(function () {
    $("#FieldFilter").keyup(function () {
 
      var value = $("#FieldFilter").val();
      var grid = $("#grid").data("kendoGrid");
 
      if (value) {
        grid.dataSource.filter({
          logic: "or",
          filters: [
            {
              field: "PurchaseId",
              operator: "eq",
              value: value
            },
            {
              field: "ContactName",
              operator: "contains",
              value: value
            },
            //{
            //  field: "PoDate",
            //  operator: "equals",
            //  value: value
            //}
          ]
        });
      } else {
        grid.dataSource.filter({});
      }
    });
  }); 
</script>

 

And the data source is a list of these:

public class OpenPurchaseOrder
{
    [Display(Name = "Supplier")]
    public string ContactName { get; set; }
    [Display(Name = "PO No")]
    public int PurchaseId { get; set; }
    public int? DeliverTo { get; set; }
    [Display(Name = "PO Type")]
    public string PoType { get; set; }
    [Display(Name = "PO Date")]
    public DateTime? PoDate { get; set; }
}

 

That works fine if I comment out either the PurchaseId filter or the ContactName filter, but if I have them both I get System.FormatException: 'Input string was not in a correct format.' .  I'm guessing that's because one column contains a string field and the other contains an int field?  Is there any way to get round that?

I'm guessing that's because 

 

 

 

 

 

2 Answers, 1 is accepted

Sort by
0
Accepted
Georgi
Telerik team
answered on 21 Sep 2018, 11:05 AM
Hi Tom,

A possible solution is to check for the type of the field and in case it is a number or a date parse its value.

e.g.

var grid = $('#grid').data('kendoGrid');
var columns = grid.columns;
 
var filter = { logic: 'or', filters: [] };
columns.forEach(function (x) {
  if (x.field) {
    var type = grid.dataSource.options.schema.model.fields[x.field].type;
    if (type == 'string') {
      filter.filters.push({
        field: x.field,
        operator: 'contains',
        value: e.target.value
      })
    }
    else if (type == 'number') {
      if (isNumeric(e.target.value)) {
        filter.filters.push({
          field: x.field,
          operator: 'eq',
          value: e.target.value
        });
      }   
 
    } else if (type == 'date') {
      var data = grid.dataSource.data();
      for (var i=0;i<data.length ; i++){
        var dateStr = kendo.format(x.format, data[i][x.field]);
        // change to includes() if you wish to filter that way https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
        if(dateStr.startsWith(e.target.value)){
          filter.filters.push({
            field: x.field,
            operator:'eq',
            value: data[i][x.field]
          })
        }
      }
    } else if (type == 'boolean' && getBoolean(e.target.value) !== null) {
      var bool = getBoolean(e.target.value);
      filter.filters.push({
        field: x.field,
        operator: 'eq',
        value: bool
      });
    }              
  }
});
grid.dataSource.filter(filter);

Below you wil find an article which demonstrates how to implement a global search using the above approach:



Regards,
Georgi
Progress Telerik
Get quickly onboarded and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers. Learn More.
0
Tom
Top achievements
Rank 1
answered on 22 Sep 2018, 01:26 PM

Hi Georgi

That's great, that worked perfectly, many thanks.

Tags
Grid
Asked by
Tom
Top achievements
Rank 1
Answers by
Georgi
Telerik team
Tom
Top achievements
Rank 1
Share this question
or