SharePoint 2013 : Set Content Search Web Part “QueryText” Attribute Programmatically

Sometimes, it may be necessary to set the “QueryText” attribute of the Content Search Web Part Programmatically :

Here’s the existing structure in “Microsoft.Office.Server.Search.dll” :


In order to override the QueryText attribute, you can override the BeforeSerializeToClient event :

public class CustomContentBySearchWebPart : ContentBySearchWebPart
    public CustomContentBySearchWebPart() { }

    protected override void OnLoad(EventArgs e)
        if (this.AppManager != null)
            if (this.AppManager.QueryGroups.ContainsKey(this.QueryGroupName) &&
                this.AppManager.QueryGroups[this.QueryGroupName].DataProvider != null)
                this.AppManager.QueryGroups[this.QueryGroupName].DataProvider.BeforeSerializeToClient +=
                    new BeforeSerializeToClientEventHandler(EnhanceQuery);


    private void EnhanceQuery(object sender, BeforeSerializeToClientEventArgs e)
        DataProviderScriptWebPart dataProvider = sender as DataProviderScriptWebPart;
        dataProvider.QueryTemplate = “ACTUAL QUERY”;
Comments (7)
  1. SP2013 says:

    dataProvider.QueryTemplate = “ACTUAL QUERY”;

    What is the format of actual query

  2. Lester Sconyers says:

    @SP2013: query would look something like below:

    dataProvider.QueryTemplate = "(owstaxidMyProperty:"some value" OR MyManagedProperty:"some value");

  3. Gautam Jaiswal says:

    I wanted to add Content Search Web Part dynamically using C# code on Feature activated event. How do I set the Query from there?


    ContentSearchWebPart csWebPart = new ContentSearchWebPart();

    //Set query here

  4. Poidl says:

    It might be easier if you use the DataProviderJson-Property. You can find an example here:…/setting-dataprovider-for.html

  5. Sharop says:

    Hi, i've been  working without success in enable the fql syntax, without using /_api/search. I mean, trying to intercept ProcessQuery and attach enablefql, and  sourceid. It's possible from here or there are another way to do this?  Thanks in advance

  6. Daryl Rasmussen says:

    I found I had to invoke  base.OnLoad(e); before the test for if (this.AppManager != null) in the onLoad event, or the setting chagnes in the EnhanceQuery method did not take effect.

  7. JC_DLS1 says:

    do you have also a jquery script that can retrieve the query text? I want to add that script on my display template and do some validations

Comments are closed.

Skip to main content