Articles in this section
Category / Section

Search operation using WebAPI service

2 mins read

Problem:

The WebAPI do not have inbuilt support to handle search query when performing search operation.

Solution:

Though ODataV4 has support for handling search queries, since WebAPI 2.2 does not have support. The search operation will not work using the Odata controller, so we need to manually handle the search query at the server side.

Please refer to the below code example.

MVC:

@(Html.EJ().Grid<object>("Grid")
   .Datasource(ds => ds.URL("/api/Values").Adaptor(AdaptorType.WebApiAdaptor))
   .AllowPaging()
   .AllowSearching()
   .ToolbarSettings(toolbar =>
    {
      toolbar.ShowToolbar().ToolbarItems(items =>
      {
         items.AddTool(ToolBarItems.Search);         
      });
    })
   .Columns(col =>
    {
      col.Field("OrderID").HeaderText("OrderID").IsPrimaryKey(true).Width(90).Add();
      col.Field("CustomerID").HeaderText("Customer ID").Width(80).Add();
      col.Field("Freight").HeaderText("Freight").Width(75).Add();
      col.Field("ShipCity").HeaderText("Ship City").Width(80).Add();
      col.Field("ShipCountry").HeaderText("Ship Country").Width(80).Add();
    })
)

 

ASP.NET:

    <asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">
    <div>
        <ej:Grid ID="FlatGrid" runat="server" AllowPaging="True" AllowSearching="true">
            <DataManager URL="api/Orders" Adaptor="WebApiAdaptor" />
            <ToolbarSettings ShowToolbar="true" ToolbarItems="search"></ToolbarSettings>
            <Columns>
                <ej:Column Field="OrderID" HeaderText="Order ID" IsPrimaryKey="True" Width="90" />
                <ej:Column Field="CustomerID" HeaderText="Customer ID" Width="80" />
                <ej:Column Field="Freight" HeaderText="Freight" Width="75" />
                <ej:Column Field="ShipCity" HeaderText="Ship City" Width="80" />
                <ej:Column Field="ShipCountry" HeaderText="Ship Country" Width="80" />
            </Columns>
        </ej:Grid>
    </div>
</asp:Content>            
            
 

 

ASP.NET CORE:

<div class="col-md-12">
            <ej-grid id="clientGrid" allow-paging="true" allow-searching="true" >
                <e-toolbar-settings show-toolbar="true" toolbar-items='@new List<string> { "search" }'></e-toolbar-settings>
                <e-datamanager adaptor="WebApiAdaptor" url="/api/values"></e-datamanager>
                <e-columns>
                    <e-column field="OrderID" header-text="Order ID" is-primary-key="true" width="90"></e-column>
                    <e-column field="CustomerID" header-text="Customer ID" width="80"></e-column>
                    <e-column field="Freight" header-text="Freight" width="75"></e-column>
                    <e-column field="ShipCity" header-text="Ship City" width="80"></e-column>
                    <e-column field="ShipCountry" header-text="Ship Country" width="80"></e-column>
                </e-columns>
            </ej-grid>
 </div>

 

Angular:

 
<ej-grid id="Grid" #grid [dataSource]="gridData" [allowPaging]="true" [allowSearching]="true" [toolbarSettings]="toolbarsettings">
    <e-columns>
        <e-column field="OrderID" headertext="Order ID" [isPrimaryKey]='true' width="90"></e-column>
        <e-column field="CustomerID" headertext="Customer ID" width="80"></e-column>
        <e-column field="Freight" headertext="Freight" width="75"></e-column>
        <e-column field="ShipCity" headertext="Ship City" width="80"></e-column>
        <e-column field="ShipCountry" headertext="Ship Country" width="80"></e-column>
    </e-columns>
</ej-grid>
 

 

export class GridComponent {
   
    public gridData: any;
 
    public toolbarsettings;
 
     constructor() {
        this.gridData = ej.DataManager({
            url: "http://localhost:49339/api/Orders",
            adaptor: new ej.WebApiAdaptor(),
            crossDomain: true
        });
 
        this.toolbarsettings = { showToolbar: true, toolbarItems: ["search"] }
       
    }
  } 
 

 

Please refer the controller code for handling the search query in controller:

public class ValuesController : ApiController
    {
        // GET api/<controller>
        ModelDataContext db = new ModelDataContext();
        public PageResult<Order> Get(ODataQueryOptions opts)
        {
            var results = db.Orders.AsQueryable();
            var count = results.Count();
            if (opts.OrderBy != null)
                results = opts.OrderBy.ApplyTo(results);
            if (opts.Filter != null)
            {
                if (opts.Filter.RawValue.Contains("substring"))
                {
                    // Seperating the value from the arguments of opts using spilt
                    string key = opts.Filter.RawValue.Split(new string[] { "'" }, StringSplitOptions.None)[1];
 
                    // Using seperated value we filter the data using Where
 
                    results = results.Where(fil => fil.CustomerID.Contains(key) || fil.EmployeeID.ToString().Contains(key) || fil.Freight.ToString().Contains(key) || fil.OrderID.ToString().Contains(key) || fil.ShipName.Contains(key) || fil.OrderDate.ToString().Contains(key) || fil.RequiredDate.ToString().Contains(key));
                }
                else
                    results = opts.Filter.ApplyTo(results, new ODataQuerySettings()).Cast<Order>();
            }
            if (opts.InlineCount != null)
                count = results.Count();
            if (opts.Skip != null)
                results = opts.Skip.ApplyTo(results, new ODataQuerySettings());
            if (opts.Top != null)
                results = opts.Top.ApplyTo(results, new ODataQuerySettings());            
            return new PageResult<Order>(results, null,count);
 
        }

 

Result:

Searched Grid

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