This article introduces some simple code which allows easy addition of search functionality which can be used to search any objects (files, .net classes) and display the search results together in a single view.
Background
This demo is presented in ASP.NET MVC so basic MVC knowledge would be useful, although this solution could be applied in other .net environments.
Using the code
The main work is done in the implementations of the abstract base class Searcher.
In this example, some dummy data is created in the constructor, this is then queried for matching items in the Search method and projected in to a SearchResult.
Note how RouteInformation is populated. The entries in the RouteInformation dictionary will be used to create an ActionLink in the MVC view.
SearchCore is initialized with a List of Searcher implementations that it should use to build the search results. When Search is called, it simply iterates over them, calling their Search method and aggregating the result.
The Search Controller
The Search controller just has a single ActionResult which creates instances of our Searchers and adds them to a list which is then passed to SearchCore. It uses a stopwatch to measure the time taken to perform the search.
Caching can be enabled on the Search method to improve performance.
Search View
The Search view simply prints the original search term and time taken, and interates over the results, printing the link (using the RouteInfoLink extension method) and then calling a DisplayTemplate for the original object (whatever that may be). The Display Templates are stored in the DisplayTemplates subfolder of the Search folder.
Display Templates
The DisplayTemplates are just standard Razor partials named after the type they are strongly-typed to.
Points of Interest
This is only a very basic implementation but shows how you can do really useful things with relatively little code.
About
Alan Parr
I am a .Net developer based in the Midlands in the UK, working on Azure, .Net Framework, .Net Core, and just generally playing around with anything that interests me. I play snooker (badly), archery (acceptably) and am a recovering Windows Phone user.