I am trying to implement search functionality on a list of customers, the functionality is detailed in this tutorial on the Asp.Net site,
In my controller i have the following
public ViewResult Index(string sortOrder, string searchString)
{
ViewBag.CustomerNameSortParm = String.IsNullOrEmpty(sortOrder) ? "CustomerName desc" : "";
ViewBag.PrimaryContactNameSortParm = sortOrder == "PrimaryContactName" ? "PrimaryContactName desc" : "PrimaryContactName";
var cust = repository.Customers;
if (!String.IsNullOrEmpty(searchString))
{
cust = cust.Where(c => c.CustomerName.ToUpper().Contains(searchString.ToUpper())
|| c.PrimaryContactName.ToUpper().Contains(searchString.ToUpper()));
}
switch (sortOrder)
{
case "CustomerName desc":
cust = repository.Customers.OrderByDescending(s => s.CustomerName);
break;
case "PrimaryContactName":
cust = repository.Customers.OrderBy(s => s.PrimaryContactName);
break;
case "PrimaryContactName desc":
cust = repository.Customers.OrderByDescending(s => s.PrimaryContactName);
break;
default:
cust = repository.Customers.OrderBy(s => s.CustomerName);
break;
}
return View(cust.ToList());
}
The if statement checks the value and should use the LINQ, WHERE statement to filter the list,
I have the textbox setup in the view like
@using (Html.BeginForm())
{
<p>
Find by name: @Html.TextBox("SearchString")
<input type="submit" value="Search" /></p>
}
However when i enter a customer name the results are not filtered, i am using SQL Server 2008 R2, has anyone else encountered this issue? is there anything else required to get the Contains method working?
And advice is appreciated?
Liam
In the sort order switch you re-set the cust variable with the repository.Customers. You should use the cust variable instead to apply the sorting on the filtered set.
when you do your search you have the if statement but it still goes onto the switch statement after, try
that way cust isnt being reassigned after its set
Edit: Since you set cust at the beginning of your method you could also have
to still order the cust without reloading it