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);
}
}
base.OnLoad(e);
}
private void EnhanceQuery(object sender, BeforeSerializeToClientEventArgs e)
{
DataProviderScriptWebPart dataProvider = sender as DataProviderScriptWebPart;
dataProvider.QueryTemplate = “ACTUAL QUERY”;
}
}