I am trying to implement a "global search" feature, that is available above our main menu, in all Views within our application. It looks like this:
The "global search" is a jQuery autocomplete input field. It resides in our _Layout.cshtml, which is a shared View and gets loaded many times by other views. Essentially it will display an auto-suggestion list for search keywords. Our list of keyword suggestions is roughly 6000 items.
Our HomeController looks like this:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Home()
{
ViewBag.Message = " Home Page.";
GlobalSearchController controller = new GlobalSearchController();
//_Layout.cshtml uses this for the auto-complete jQuery list
var suggestions = controller.GetGlobalSearchSuggestions();
return View(suggestions);
}
public ActionResult SearchResults()
{
ViewBag.Message = "Search Results page.";
GlobalSearchController controller = new GlobalSearchController();
var searchKeyword = "technology";
//SearchResults.html uses this for the search results data
var results = controller.GetGlobalSearchResults(searchKeyword);
ViewBag.SearchKeyword = searchKeyword;
return View(results);
}
}
_Layout.cshtml uses this model:
@model MyApplication.Models.GlobalSearchSuggestions
SearchResults.cshtml uses this model:
@model IQueryable<MyApplication.Models.GlobalSearchResult>
My problem begins when I use the @model declarative in _Layout.cshtml.
I get an error like this:
Message = "The model item passed into the dictionary is of type 'System.Web.Mvc.HandleErrorInfo', but this dictionary requires a model item of type 'MyApplication.Models.GlobalSearchSuggestions'."
If I remove the model declarative for _Layout.cshtml, and retrieve the "suggestions" through another means (like AJAX), it will allow the SearchResults.cshtml to work. No error is produced. But I would much rather use the model instead of AJAX. So, if I leave the model declarative in the _Layout.cshtml, I get the exception.
I also cannot load the "suggestions" from any View other than Home. Why is that? If I go to another view within our application, and I try to perform a "global search" from our _Layout.cshtml widget, I do not get any "suggestions" or data in the jQuery autocomplete. Why does it only work for the Home view and Home controller??
How do I avoid this exception and use both @model declaratives? And how can I get _Layout.cshtml to consistently display suggestions in the auto-complete field (and not just from the Home page?)?
Any help is appreciated. Thank you!