Tuesday, February 4, 2014

Add search query text programmatically for Search Results webpart - SharePoint 2013

When we programmatically add a Search Results web part, it is often a requirement to provide the search query text dynamically. Search query text is used to obtain a relevant set of search results based on the query provide. Keyword Query Language (KQL) is used to build the query text. You can learn more on building the query text by referring this article.

I used following code block within an event receiver to do the task. In this example my search query is such that all documents except .aspx web pages within the site are returned.

  1. var web = properties.Feature.Parent as SPWeb;
  2. //create search results webpart
  3. var resultsWebPart = new ResultScriptWebPart();
  4. resultsWebPart.Title = "Team Search Results";
  5. var querySettings = new DataProviderScriptWebPart
  6. {
  7.     PropertiesJson = resultsWebPart.DataProviderJSON
  8. };
  9.  
  10. //setting the search query text
  11. querySettings.Properties["QueryTemplate"] =
  12.    "(IsDocument:True) Path:{Site.URL} -FileName:*.aspx";
  13. resultsWebPart.DataProviderJSON = querySettings.PropertiesJson;
  14.  
  15. //add the search results webpart to the page
  16. var homePage = web.GetFile("SitePages/Home.aspx");
  17. using (var webPartManager = homePage.GetLimitedWebPartManager(PersonalizationScope.Shared))
  18. {
  19.     webPartManager.AddWebPart(resultsWebPart, "Left", 0);
  20.     homePage.Update();
  21. }

This will add the webpart with expected results as below

image

2 comments:

Kati said...

Hi,

I'm creating a page layout using Sharepoint Designer 2013. I'm adding content search webparts into the page layout and would like to add a page title to the query in the content search web part. This sounds a lot like the problem that you described on the post.

Can this be done for content search webpart also? Is it possible with plain ASPX or do I need Visual Studio?

Br,
Kati

Alalal said...

i tried to find answer all day and this topic helped me to resolve my problem