tags:

views:

88

answers:

2

I have a website that has PageContent, News, Events etc and I have a controller that will handle the search.

In that controller action method I guess I do a var results = SearchClass.Search(searchstring) to keep the logic out of the controller.

However because I am returning different results because I am searching News, Events etc how do I return the results as they are different models. Do I use a ViewModel and then pass that to the view? return View(SearchModel);

UPDATE: I knocked this up, what do you think:

public ActionResult Search(string criteria)
        {
            var x = WebsiteSearch.Search(criteria);
            return View(x);
        }

 public static class WebsiteSearch
    {
        public static SearchViewModel Search(string SearchCriteria)
        {
            return new SearchViewModel(SearchCriteria);

        }
    }

public class SearchViewModel
    {
        private string searchCriteria = String.Empty;

        public IEnumerable<News> NewsItems
        {
            get { return from s in News.All() where s.Description.Contains(searchCriteria) || s.Summary.Contains(searchCriteria) select s; }
        }

        public IEnumerable<Event> EventItems
        {
            get { return from s in Event.All() where s.Description.Contains(searchCriteria) || s.Summary.Contains(searchCriteria) select s; }
        }

        public SearchViewModel(string SearchCriteria)
        {
            searchCriteria = SearchCriteria;
        }

    }
A: 

You could make all the PageContent, News and Events classes implement a common interface and then return a list of searchable items. In the view you could iterate over the items and format them in an appropriate partial.

Darin Dimitrov
A: 

i was going to comment with a similar idea to Darin's. Create an interface that you implememnt on any of your searchable class model members. in fact, I'd suggest using two distinct interfaces, one for the search parameters and another for the 'list' of results returned. i.e. along the lines of:

public interface ISearchParameters
{
    // quick and dirty - the 'key' 'COULD' be the db column
    // and the 'value' the search value for that column
    // as i said, quick and dirty for the purposes of demonstration
    IDictionary<string, string> SearchTokens { get; set; }
}

// return a 'list' of matching entries which when clicked, 
// will navigate to the url of the matching 'page'
public interface ISearchResults
{   
    string URLLink{ get; set; }
    string Description{ get; set; }
}

Hope this creates at least some thought on the subject...

jim