从两个字段的视图中键入的搜索字符串'名字'和'姓氏'综合

时间:2017-07-11 19:27:52

标签: asp.net asp.net-mvc asp.net-mvc-5

目前,我有一个搜索框,以便在您输入任何内容时,会显示该关键字。但是如果我想键入两个关键字,我想返回这些组合关键字并从数据库中找到它。

在控制器中使用我的Index方法:

            if (!String.IsNullOrEmpty(searchString))
        {
            result = result.Where(b =>
                b.LastName.Contains(searchString) || b.FirstName.Contains(searchString)
                || b.Id.ToString().Contains(searchString)
                || b.Email.Contains(searchString)
                || b.City.Contains(searchString)
                || b.State.ToString().Contains(searchString)
                || b.FirstName.Contains(searchString)
                || b.FirstName.Contains(searchString) && b.LastName.Contains(searchString) // was trying to do something like this... I tried adding a FullName property and concactenated FirstName and LastName... didn't like it
                );
            ...
        }

查看:

@Html.TextBox("SearchString", ViewBag.CurrentFilter as string, new { @class = "form-control", @placeholder = "Search first name, last name, city, state, ID", @type = "search" })

当您使用两个字段进行搜索时,它会显示:

http://localhost:59818/Broker?SearchString=Some+Name

没有结果。显然我设置错了?或者是否可以关注我当前的架构,以便我可以简单地传递组合关键字并显示它?感谢。

1 个答案:

答案 0 :(得分:1)

您需要将这些单词拆分为数组。

var query = _context.Users.AsQueryable();

if (!String.IsNullOrEmpty(searchString))
{
   string[] collection = searchString.Split(' ', ',');
   foreach(var item in collection)
   {    
      query = query.Where(b =>
                b.LastName.Contains(item) 
                || b.FirstName.Contains(item)
                || b.Id.ToString().Contains(item)
                || b.Email.Contains(item)
                || b.City.Contains(item)
                || b.State.Contains(item));
   }
}

var result = query.ToList();

注意: 如果您的or语句过多,则会降低查询速度。