Highlight query matches in EPiServer Find search results
3 minutes
Create a view model for the search page (optional)
We create a basic view model that we will pass on to our search page to enable easy access to the search page itself as well as the search result:
public class SearchPageViewModel
{
public SearchPage CurrentPage { get; set; }
public UnifiedSearchResults SearchResult { get; set; }
public string Keywords { get; set; }
public SearchPageViewModel(SearchPage page, UnifiedSearchResults results, string keywords)
{
CurrentPage = page;
SearchResult = results;
Keywords = keywords;
}
}
Specify highlight settings
For each search result hit we want a title and an excerpt where matching words have been highlighted. In order to achieve this we will pass a HitSpecification object to the GetResult method:
public class SearchPageController : PageController<SearchPage>
{
public ActionResult Index(SearchPage currentPage, string q)
{
UnifiedSearchResults searchResult = null;
if (!string.IsNullOrWhiteSpace(q))
{
// Specify highlight settings
var hitSpecification = new HitSpecification { HighlightExcerpt = true, HighlightTitle = true };
// Search
searchResult = SearchClient.Instance.UnifiedSearchFor(q).GetResult(hitSpecification);
}
// Return the search result view
return View(new SearchPageViewModel(currentPage, searchResult, q));
}
}
Render the search result
To display each search result item we’ll add the following to our search result view:
@if (Model.SearchResult != null)
{
<div id="search-results">
<p>Displaying the top @Model.SearchResult.Count() hits out of a total of @Model.SearchResult.TotalMatching matching your search for <em>@Model.Keywords</em>.</p>
@foreach (UnifiedSearchHit result in Model.SearchResult)
{
<a href="@result.Url">
<h2>@Html.Raw(result.Title)</h2>
<p>@Html.Raw(result.Excerpt)</p>
</a>
}
</div>
}
Customize highlight styling
Each UnifiedSearchHit has an Excerpt and a Title property. These will contain HTML code where each highlight is an <em> element (this is why I use the Html.Raw() helper method to render them).
In order to customize the styling of each highlight we’ll add some CSS like this:
#search-results em
{
background-color: rgba(255, 255, 255, 0.8);
border-radius: 3px 3px 3px 3px;
box-shadow: 0 1px #FFFFFF inset;
font-style:normal;
}
This gives us a search result view like the following: