2009-11-27 79 views
0

我有一个网站,有PageContent,新闻,事件等,我有一个控制器,将处理搜索。实现网站搜索的最佳MVC实践

在该控制器的行动方法,我想我做一个var results = SearchClass.Search(searchstring)保持逻辑的控制器。

但是因为我正在返回不同的结果,因为我正在搜索新闻,事件等,我如何返回结果,因为它们是不同的模型。我是否使用ViewModel并将其传递给视图? return View(SearchModel);

更新:我敲了这件事,你有什么感想:

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; 
     } 

    } 

回答

0

我打算用类似的想法评论Darin's。创建一个您在任何可搜索的类模型成员上实现的接口。实际上,我建议使用两个不同的接口,一个用于搜索参数,另一个用于返回结果的“列表”。沿着线即:

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; } 
} 

希望这会造成对主题至少有一些想法...

0

你可以让所有的PageContentNewsEvents类实现一个共同的接口,然后返回搜索项的列表。在视图中,您可以遍历这些项目并将它们格式化为适当的部分。