Reputation: 141
I've been trying all day to adapt the following tutorial to search multiple columns.
https://docs.asp.net/en/latest/tutorials/first-mvc-app/search.html
It works fine to search a single column. My problem is that I'd like to search more than a single column for the keyword, everything I have tried has resulted in similar behaviour where the result is acting as an 'And' instead of an 'Or' operator (so if it appears in both columns it works, rather than being in either column). I have tried 'case' statements 'if else' etc but my logic has let me down. I like to search for presence in either column
My controller code
public ActionResult Search(string searchString)
{
var ClipQry = from m in db.Incidents
orderby m.ClipName
select m.ClipName;
var SearchResult = from LoopVar in db.Incidents
select LoopVar;
if (!String.IsNullOrEmpty(searchString))
{
SearchResult = SearchResult.Where(s => s.ClipName.Contains(searchString));
}
return View("Search", SearchResult);
}
The View code
<form asp-controller="Incidents" asp-action="Index" method="get">
<p>
<input type="text" name="SearchString" class="form-control" placeholder="Search...">
</p>
</form>
I have tried things as follows but it only results in same behaviour of acting as an 'And' operator
if (!String.IsNullOrEmpty(searchString))
{
SearchResult = SearchResult.Where(s => s.ClipName.Contains(searchString));
SearchResult = SearchResult.Where(y => y.ClipKeywords.Contains(searchString));
}
Upvotes: 1
Views: 3941
Reputation: 218732
Your current code is doing filtering on the ClipName
property first and assigning the result to SearchResult
variable. Then in the second line you are doing the filter on the ClipKeywords
property on the same result (SearchResult
, which is the filtered result from the previous line). So effectively you are doing an AND here.
You can do OR in your where clause.
if (!String.IsNullOrEmpty(searchString))
{
SearchResult = SearchResult
.Where(s => s.ClipName.Contains(searchString)
||s.ClipKeywords.Contains(searchString));
}
Upvotes: 4