Articles in this section
Category / Section

Perform search operation using ODataV4Adaptor in ASP.NET MVC Grid.

5 mins read

This knowledge base explains how to perform search operation using OdataV4 Adaptor in ASP.NET MVC Grid

Solution

In Web API 2.2 OData, $search query is not yet supported and hence it throws 404 exceptions while searching. To perform search operation using OdataV4 adaptor the custom adaptor can be used.

1.Render the Grid control.

HTML

<div id="Grid"></div>

 

JS

<script type="text/javascript">
          $(function () {
            $("#Grid").ejGrid({
                dataSource: ej.DataManager({
                url: "/odata/Orders",
                adaptor: new ej.ODataV4Adaptor(),
                crossDomain: true
                }),
                toolbarSettings : { showToolbar : true, toolbarItems : ["search"] },
                allowSearching : true,
                allowPaging : true,
                actionBegin:"actionBegin", 
                load:"onLoad",
                columns: [
                         { field: "OrderID", headerText: “Order ID”, isPrimaryKey:true, width: 75},
                         { field: "CustomerID", headerText: “Customer ID”,  width: 75},
                         { field: "EmployeeID", headerText: “Employee ID”,  width: 75 },
                         { field: "Freight", headerText: “Freight”,  width: 75 },                                              
                         { field: "ShipCity", headerText: “ShipCity”, width: 75}
                ]
            });  
        });
</script>

 

C#

namespace EJGrid.Controllers
{
    public class OrdersController : ODataController
    {
        // GET: Orders
        NORTHWNDEntities db = new NORTHWNDEntities();
 
        [EnableQuery]
        public IQueryable<Order> Get()
       {
            List<Order> emp = db.Orders.ToList();
            return emp.AsQueryable();
        }    
   }
}

 

MVC

 
@(Html.EJ().Grid<object>("Grid")
           .Datasource(ds => { ds.URL("/odata/Orders").Adaptor(AdaptorType.ODataV4Adaptor); })
           .ToolbarSettings(toolbar =>
           {
             toolbar.ShowToolbar().ToolbarItems(items =>
             {
               items.AddTool(ToolBarItems.Search);
             });
           })
           .AllowSearching(true)
           .AllowPaging(true)
           .ClientSideEvents(eve => eve.Load("onLoad").ActionBegin("actionBegin"))
           .Columns(col =>
           {
            col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width(75).Add();
            col.Field("CustomerID").HeaderText("Customer ID").Width(75).Add();
            col.Field("EmployeeID").HeaderText("Employee ID").Width(75).Add();
            col.Field("Freight").HeaderText("Freight").Width(75).Add();
            col.Field("ShipCity").HeaderText("ShipCity").Width(75).Add();
           }))

 

C#

namespace EJGrid.Controllers
{
    public class OrdersController : ODataController
    {
        // GET: Orders
        NORTHWNDEntities db = new NORTHWNDEntities();
 
        [EnableQuery]
        public IQueryable<Order> Get()
       {
            List<Order> emp = db.Orders.ToList();
            return emp.AsQueryable();
        }    
   }
}

 

ASP

<ej:Grid runat="server" ID="FlatGrid" AllowPaging="true" AllowSearching="true">
        <DataManager URL="/odata/Orders"  Adaptor="ODataV4Adaptor" />
        <ToolbarSettings ShowToolbar="True" ToolbarItems="search"></ToolbarSettings>
        <ClientSideEvents ActionBegin="actionBegin" Load="onLoad" />
        <Columns>
            <ej:Column Field="OrderID" HeaderText="Order ID" IsPrimaryKey="true" Width="75" />
            <ej:Column Field="CustomerID" HeaderText="Customer ID" Width="75" />
            <ej:Column Field="EmployeeID" HeaderText="Employee ID" Width="75" />
            <ej:Column Field="Freight" HeaderText="Freight" Width="75" />
            <ej:Column Field="ShipCity" HeaderText="ShipCity" Width="75" />
        </Columns>
</ej:Grid>

 

C#

namespace EJGrid.Controllers
{
    public class OrdersController : ODataController
    {
        // GET: Orders
        NORTHWNDEntities db = new NORTHWNDEntities();
 
        [EnableQuery]
        public IQueryable<Order> Get()
       {
            List<Order> emp = db.Orders.ToList();
            return emp.AsQueryable();
        }    
   }
}

 

2.In customAdaptor we have extended the OdataV4Adaptor and modified the search query to act as filter query.

In actionBegin event we have used contains operator for the string columns and equals operator for the number columns. So, we have assigned the search fields manually depending on the type of the column. In load event we have assigned the customAdaptor to the grid dataSource.

<script> 
var customAdaptor = new ej.ODataV4Adaptor().extend({ 
        onEachSearch: ej.ODataAdaptor.prototype.onEachSearch, 
        onSearch: ej.ODataAdaptor.prototype.onSearch, 
        onPredicate: function (pred, query, requirescast) { 
            var returnvalue = "", 
                val = pred.value, 
                isdate = val instanceof Date; 
            pred.ignoreCase = false; 
            if (!isNaN(parseInt(val, 10))) { 
                pred.operator = "equal"; 
                pred.value = parseInt(val, 10); 
            } 
            ej.data.odUniOperator["contains"] = "contains"; 
            returnvalue = ej.ODataAdaptor.prototype.onPredicate.call(this, pred, query, requirescast); 
            if (isdate) 
                returnvalue = returnvalue.replace(/datetime'(.*)'$/, "$1"); 
            return returnvalue; 
        } 
    })                                                                                                
 
    function onLoad(args) { 
        this.model.dataSource.adaptor = new customAdaptor(); 
    } 
 
function actionBegin(args) { 
       if (args.requestType == "searching") { 
            var p = parseInt(args.keyValue), type; 
            if (isNaN(p))           // find type of searching value
                type = "string";
            else
                type = "number";
            var cols = ej.DataManager(this.model.columns).executeLocal(newej.Query().where("type", "==", type));  // get columns which have type as searching value type 
           this.model.searchSettings.fields = ej.distinct(cols, "field", false); // assign search fields        } 
    }
</script> 

 

ANGULAR

HTML

<ej-grid id="Grid" #grid23 [dataSource]="gridData2" [toolbarSettings]="toolbarItems" [allowSearching]="true"  [allowPaging]="true"  (actionBegin)="actionBegin($event)" (load)="onLoad($event)" >
    <e-columns>
        <e-column field="OrderID" headertext="Order ID" [isPrimaryKey]="true" width="75"></e-column>
        <e-column field="CustomerID" headertext="Customer ID" width="75"></e-column>
        <e-column field="EmployeeID" headerText= "Employee ID" width="75"></e-column>
        <e-column field="Freight" headertext="Freight" width="75"></e-column>
        <e-column field="ShipCity" headertext="ShipCity" width="75"></e-column>
    </e-columns>
</ej-grid>

 

TS

import { Component, ViewEncapsulation, ViewChild, AfterViewInit } from '@angular/core';
import {CommonModule} from "@angular/common";
import {EJComponents } from 'ej-angular2/src/ej/core';
 
@Component({
    selector: 'ej-app',
    templateUrl: 'src/grid/grid.component.html',
})
export class GridComponent  {
    public gridData2: any;
    public toolbarItems;
    public customAdaptor;   
    @ViewChild('grid23') Grid: EJComponents<any, any>;
    constructor() {     
        this.toolbarItems = { showToolbar: true, toolbarItems: ["search"] };
        this.gridData2 = new ej.DataManager({          
            url:"/odata/Orders",
            adaptor: new ej.ODataV4Adaptor(),
            crossDomain: true
        });
    }
    actionBegin(args: any) {
        var gridObj = $("#Grid").ejGrid("instance");
        if (args.requestType == "searching") {
            var p = parseInt(args.keyValue), type;
            if (isNaN(p))           // find type of searching value
                type = "string";
            else
                type = "number";
            var cols = ej.DataManager(gridObj.model.columns).executeLocal(new ej.Query().where("type", "==", type));  // get columns which have type as searching value type
            gridObj.model.searchSettings.fields = ej.distinct(cols, "field", false); // assign search fields        }
        }    
}
onLoad(e:any){
    var customAdaptor: any =  new ej.ODataV4Adaptor().extend({
        onEachSearch: ej.ODataAdaptor.prototype.onEachSearch,
        onSearch: ej.ODataAdaptor.prototype.onSearch,
        onPredicate: function (pred, query, requirescast) {
            var returnvalue = "",
                val = pred.value,
                isdate = val instanceof Date;
            pred.ignoreCase = false;
            if (!isNaN(parseInt(val, 10))) {
                pred.operator = "equal";
                pred.value = parseInt(val, 10);
            }
            ej.data.odUniOperator["contains"] = "contains";
            returnvalue = ej.ODataAdaptor.prototype.onPredicate.call(this, pred, query, requirescast);
            if (isdate)
                returnvalue = returnvalue.replace(/datetime'(.*)'$/, "$1");
            return returnvalue;
        }
    })
    this.gridData2.adaptor = new customAdaptor();
}
} 

 

Result

initial rendering of the grid

Figure 1Initial Rendering of Grid

searching in the Grid

Figure 2After Searching in Grid


Conclusion

I hope you enjoyed learning about how to Perform search operations using ODataV4Adaptor in ASP.NET MVC Grid.

You can refer to our ASP.NET MVC Grid feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our ASP.NET MVC Grid example to understand how to create and manipulate data.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forumsDirect-Trac, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please sign in to leave a comment
Access denied
Access denied