Set QueryTemplate programmatically to a Content By Search Web Part
Sometimes, it may be necessary to set the “QueryText” attribute of the Content Search Web Part Programmatically :
In order to override the QueryText attribute, you can override the BeforeSerializeToClient event :
Programmatically change Content by Search queryTemplate
Add search query text programmatically for Search Results WebPart - SharePoint 2013
SharePoint 2013 Content Search WebPart
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);
}
/// <summary>
/// BeforeSerializeToClientEventArgs Event: called before sending the query template to search /// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void EnhanceQuery(object sender, BeforeSerializeToClientEventArgs e)
{
try
{
DataProviderScriptWebPart dataProvider = sender as DataProviderScriptWebPart;
StringBuilder qry = new StringBuilder();
qry.Append("owstaxidMyProperty1:xyz;owstaxidMyProperty2:123;");
dataProvider.QueryTemplate = qry.ToString();
}
catch (Exception ex)
{
//exception code
}
}
}
SharePoint 2013 : Set Content Search Web Part “QueryText” Attribute Programmatically Programmatically change Content by Search queryTemplate
Add search query text programmatically for Search Results WebPart - SharePoint 2013
SharePoint 2013 Content Search WebPart
Post a Comment