如何在基本的Web应用程序中创建搜索页面和功能

时间:2013-05-17 00:16:51

标签: model-view-controller search controller

我有一个相当简单的MVC webapp连接到数据库。用户需要一个搜索页面,该页面将从单个表中提取某些记录。用户可以提供一个或多个关键字。搜索功能必须在3个不同的列中搜索包含这些关键字的记录:title,description或poc。

我有以下设置,但不正确。它提供包含任何关键字的记录。结果必须是包含所有关键字的记录。另外,我不确定这是否是编写搜索功能的最佳方式......

// searchString contains all keywords delimited by spaces
string[] keywordArray = Regex.Split(searchString, "\\s");

var model = new List<MyTable>();
foreach (string word in keywordArray)
{
   foreach (var record in myTableRepository.MyTable.Where(x => x.title.ToLower().Contains(word.ToLower()) || (x.description != null && x.description.ToLower().Contains(word.ToLower())) || (x.poc != null && x.poc.ToLower().Contains(word.ToLower()))).ToList())
   {
       model.Add(new MyTable
       {
          id = record.id,
          title = record.title,
          description = record.description, 
          poc = record.poc
       });
   }
}
return View(model);

例如,如果用户给出了以下搜索条件“john test phase”,那么结果可能如下所示:

title                   description                  poc
Lorem Ipsum Test A      Phase A lorem ipsum          john doe
Lorem Ipsum phase       This is john test for jack   jane doe
Lorem Ipsum             John test for jim            clark phase

等。

提前感谢您的建议和提示!

1 个答案:

答案 0 :(得分:1)

最好一次搜索一条记录并检查一条记录中的所有关键字。也许你可以在一个变量中收集与特定条目相关的所有单词,然后搜索所有关键字。

// searchString contains all keywords delimited by spaces
string[] keywordArray = Regex.Split(searchString, "\\s");

var model = new List<MyTable>();
Boolean searchResult;
foreach (var record in myTableRepository.MyTable)
{
    searchResult = true;

    var recordTerms = record.title + " " + record.description + " " + record.poc;
    recordTerms = recordTerms.toLower();
    recordArray = Regex.Split(recordTerms, "\\s");

    foreach (var word in keywordArray)
    {
        if (!recordArray.asList.contains(word))
            searchResult = false;
        }
    }

    if (searchResult) {
        model.Add(new MyTable
        {
            id = record.id,
            title = record.title,
            description = record.description, 
            poc = record.poc
        });
    }
}
return View(model);