SharePoint 2010 內建搜尋 Web 部件(核心結果、最佳比對、精簡面板等)已滿足大多數需求,但超級使用者與開發人員仍可透過繼承 `CoreResultsWebPart` 建立客製化搜尋體驗。本文完整示範:繼承核心結果 Web 部件、自訂資料來源與檢視、覆寫 `AddSortOrder` 實現多欄位排序、建立 EditorPart 限制可排序欄位、部署與效果驗證。
[ToolboxItem(false)]
public class MSDNSample : CoreResultsWebPart
{
public MSDNSample() { } // 序列化必要
protected override void CreateChildControls()
{
base.CreateChildControls();
// 加入自訂 UI 控制項(如排序下拉清單)
}
protected override void CreateDataSource()
{
// base.CreateDataSource();
this.DataSource = new MyCoreResultsDataSource(this);
}
}
public class MyCoreResultsDataSource : CoreResultsDatasource
{
public MyCoreResultsDataSource(CoreResultsWebPart parent) : base(parent)
{
this.View = new MyCoreResultsDataSourceView(this, "MyCoreResults");
}
}
public class MyCoreResultsDataSourceView : CoreResultsDatasourceView
{
public MyCoreResultsDataSourceView(SearchResultsBaseDatasource owner, string viewName)
: base(owner, viewName)
{
if (owner == null) throw new ArgumentNullException("owner");
var ds = owner as MyCoreResultsDataSource;
this.QueryManager = SharedQueryManager.GetInstance(ds.ParentWebpart.Page).QueryManager;
}
public override void AddSortOrder(SharePointSearchRuntime runtime)
{
if (runtime.KeywordQueryObject == null) return;
runtime.KeywordQueryObject.SortList.Clear(); // 移除預設排序
var wp = this.DataSourceOwner.ParentWebpart as SearchResultsPart;
string sortField = wp.SortFields; // 來自 EditorPart 設定
if (!string.IsNullOrEmpty(sortField))
{
if (wp.Page.IsPostBack)
{
// 使用者在頁面選擇的欄位與方向
string field = wp.Page.Request.Form[SearchResultsPart.mFormSortField];
SortDirection dir = wp.Page.Request.Form[SearchResultsPart.mFormSortDirection] == "ASC"
? SortDirection.Ascending : SortDirection.Descending;
runtime.KeywordQueryObject.SortList.Add(field, dir);
}
else
{
// 預設取第一個欄位,降序
string[] fields = sortField.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
runtime.KeywordQueryObject.SortList.Add(fields[0], SortDirection.Descending);
}
}
else
{
base.AddSortOrder(runtime); // 回退預設
}
}
}
只有符合下列條件的受管理屬性可用於排序:
程式碼結構與 SharePoint 2007 相同,此處略過細節。
透過繼承 `CoreResultsWebPart` 三層架構,僅覆寫核心排序邏輯即可賦予搜尋結果彈性排序能力,並搭配 EditorPart 提供使用者友善設定介面。此模式同樣適用於分頁、群組、自訂排名模型等進階搜尋客製化需求。