我正在尝试在客户列表上实现搜索功能,本教程在Asp.Net网站上详细介绍了该功能,
在我的控制器中,我有以下
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());
}
if语句检查该值,并应使用LINQ,WHERE语句来过滤列表,
我在视图中设置了文本框,如
@using (Html.BeginForm())
{
<p>
Find by name: @Html.TextBox("SearchString")
<input type="submit" value="Search" /></p>
}
但是,当我输入客户名称时结果未被过滤,我使用的是SQL Server 2008 R2,还有其他人遇到过这个问题吗?还有其他任何东西需要让Contains方法工作吗?
建议表示赞赏?
利安
答案 0 :(得分:2)
在排序顺序开关中,您使用repository.Customers重新设置cust变量。您应该使用cust变量来对已过滤的集合应用排序。
switch (sortOrder)
{
case "CustomerName desc":
cust = cust.OrderByDescending(s => s.CustomerName);
break;
答案 1 :(得分:0)
当你进行搜索时,你有if语句但是仍然会在转换语句之后,尝试
if (!String.IsNullOrEmpty(searchString))
{
cust = cust.Where(c => c.CustomerName.ToUpper().Contains(searchString.ToUpper())
|| c.PrimaryContactName.ToUpper().Contains(searchString.ToUpper()));
}
else
{
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;
}
}
这种方式不会在设置
后重新分配编辑:由于您在方法开头设置了cust,您也可以
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 = cust.OrderByDescending(s => s.CustomerName);
break;
case "PrimaryContactName":
cust = cust.OrderBy(s => s.PrimaryContactName);
break;
case "PrimaryContactName desc":
cust = cust.OrderByDescending(s => s.PrimaryContactName);
break;
default:
cust = cust.OrderBy(s => s.CustomerName);
break;
}
仍然在不重新加载的情况下订购它