)
We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. (Last updated on: June 24, 2019).
Unfortunately, activation email could not send to your email. Please try again.
Essential JS2

Syncfusion jQuery based widgets are no longer in active development. Switch to our pure JavaScript based next generation Essential JS 2 library.

Syncfusion Feedback

Search operation using WebAPI service

Platform: jQuery |
Control: ejGrid |
Published Date: December 27, 2017 |
Last Revised Date: February 26, 2020
Tags: search

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

ADD COMMENT
You must log in to leave a comment

Please sign in to access our KB

This page will automatically be redirected to the sign-in page in 10 seconds.

Up arrow icon

Warning Icon You are using an outdated version of Internet Explorer that may not display all features of this and other websites. Upgrade to Internet Explorer 8 or newer for a better experience.Close Icon

Live Chat Icon For mobile
Live Chat Icon