Sometimes we need to programmatically set search result source and a custom item display template to a search web part.
Following is a sample code segment to do the needful
- //Get the instance of web part
- var homePage = web.GetFile("SitePages/Home.aspx");
- using (var webPartManager = homePage.GetLimitedWebPartManager(PersonalizationScope.Shared))
- {
- var recentDocs = webPartManager.WebParts.Cast<WebPart>().FirstOrDefault
- (wp => wp.Title.Equals("Recent Documents")) as ResultScriptWebPart;
- var querySettings = new DataProviderScriptWebPart
- {
- PropertiesJson = recentDocs.DataProviderJSON
- };
- //Get the search service application proxy
- var settingsProxy = SPFarm.Local.ServiceProxies.GetValue
- <SearchQueryAndSiteSettingsServiceProxy>();
- var searchProxy = settingsProxy.ApplicationProxies.GetValue
- <SearchServiceApplicationProxy>("Search Service Application");
- var siteOwner = new SearchObjectOwner(SearchObjectLevel.SPSite, web);
- //Set the result source. I set the default for demonstration
- var siteResultSource = searchProxy.GetResultSourceByName("Local SharePoint Results", siteOwner);
- querySettings.Properties["SourceName"] = siteResultSource.Name;
- querySettings.Properties["SourceID"] = siteResultSource.Id;
- querySettings.Properties["SourceLevel"] = siteOwner.Level;
- //Set the item display template
- recentDocs.ItemTemplateId = "~sitecollection/_catalogs/masterpage/Display Templates/Search/Item_Contoso.js";
- recentDocs.DataProviderJSON = querySettings.PropertiesJson;
- webPartManager.SaveChanges(recentDocs);
- }
- homePage.Update();
That’s all we need to do.
1 comment:
Hi Dinusha
Thanks for this post, I found it really useful. One question though, do the search settings on the target web site affect whether this will work? For example, does the "Inherit search settings" option need to be unchecked for it to work or will it just override it regardless?
Many thanks
Tim
Post a Comment