Rockyy
Rockyy

Reputation: 283

ASP:NET MVC multiple words in search

I having trouble finding out how to handle multiple words when the user searches. An example: Search: "Blue box" it should be able to find: "One box is blue". How would I do this? This is basically how my controller looks like atm:

public ActionResult Index(string searchString)
{
    var posts = from s in _context.Posts
                   select s;

    var postIndexViewModel = new PostIndexViewModel();

    if (!String.IsNullOrEmpty(searchString))
    {
            posts = posts.Where(s => s.Title.Contains(searchString));
     }

    // More code here

    return View(postIndexViewModel);

}

Upvotes: 2

Views: 3378

Answers (3)

SALIU OLADITAN
SALIU OLADITAN

Reputation: 1

This works perfectly well for me. See the code snippet and the screenshot below:

string[] SplitValue = StaffSearch.Split(",");

List<HistorypodScans> query = new List<HistorypodScans>();

foreach (var word in SplitValue)
{
      var staffquery = _db.HistorypodScans.Where(x => x.Waybillnumber.Contains(word) || x.AWBNO.Contains(word)).ToList();
      query.AddRange(staffquery);

}

return View(query);


[enter image description here][1]     

[1]: https://i.sstatic.net/TRmMW.jpg Multiple Words Search Result

Upvotes: 0

Jamie Rees
Jamie Rees

Reputation: 8183

Your problem is that you are doing the contains with a whole string. That means it must contain "Blue box" in that order.

This is what you need to do:

var strings = searchString.Split(' ');
var finalPosts = new List<string>();
if (!String.IsNullOrEmpty(searchString))
{
    foreach (var splitString in strings)
    {
        finalPosts.Add(posts.FirstOrDefault(s => s.Title.Contains(splitString)));
    }     
}

The finalPosts list then contains your results.

Upvotes: 3

Yang Zhang
Yang Zhang

Reputation: 4570

One way I can think of is to search term by term by splitting search string passed in.

public ActionResult Index(string searchString)
{
    var posts = from s in _context.Posts
                   select s;

    var postIndexViewModel = new PostIndexViewModel();

    if (!String.IsNullOrEmpty(searchString))
    {
        var terms = searchString.Trim().Split(' ');
        posts = posts.Where(s => terms.Any(terms.Contains));
     }

    // More code here

    return View(postIndexViewModel);

}

Upvotes: 1

Related Questions