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.
- var web = properties.Feature.Parent as SPWeb;
- //create search results webpart
- var resultsWebPart = new ResultScriptWebPart();
- resultsWebPart.Title = "Team Search Results";
- var querySettings = new DataProviderScriptWebPart
- {
- PropertiesJson = resultsWebPart.DataProviderJSON
- };
- //setting the search query text
- querySettings.Properties["QueryTemplate"] =
- "(IsDocument:True) Path:{Site.URL} -FileName:*.aspx";
- resultsWebPart.DataProviderJSON = querySettings.PropertiesJson;
- //add the search results webpart to the page
- var homePage = web.GetFile("SitePages/Home.aspx");
- using (var webPartManager = homePage.GetLimitedWebPartManager(PersonalizationScope.Shared))
- {
- webPartManager.AddWebPart(resultsWebPart, "Left", 0);
- homePage.Update();
- }
This will add the webpart with expected results as below