Rockyy Rockyy - 1 month ago 10
ASP.NET (C#) Question

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

}

Answer

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.