Share via


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” :

window

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);
            }
        }

        base.OnLoad(e);
    }

    private void EnhanceQuery(object sender, BeforeSerializeToClientEventArgs e)
    {    
        DataProviderScriptWebPart dataProvider = sender as DataProviderScriptWebPart;
        dataProvider.QueryTemplate = “ACTUAL QUERY”;
    }
}

Comments

  • Anonymous
    January 20, 2013
    dataProvider.QueryTemplate = “ACTUAL QUERY”; What is the format of actual query

  • Anonymous
    January 25, 2013
    @SP2013: query would look something like below: dataProvider.QueryTemplate = "(owstaxidMyProperty:"some value" OR MyManagedProperty:"some value");

  • Anonymous
    April 08, 2013
    I wanted to add Content Search Web Part dynamically using C# code on Feature activated event. How do I set the Query from there? Example: ContentSearchWebPart csWebPart = new ContentSearchWebPart(); //Set query here

  • Anonymous
    April 18, 2013
    It might be easier if you use the DataProviderJson-Property. You can find an example here: carepoint.blogspot.co.at/.../setting-dataprovider-for.html

  • Anonymous
    July 30, 2013
    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

  • Anonymous
    June 16, 2014
    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.

  • Anonymous
    October 12, 2014
    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