Asp.Net MVC3添加搜索功能 [英] Asp.Net MVC3 adding search functionality
问题描述
我正在尝试在客户列表中实现搜索功能,本教程在Asp.Net网站上详细介绍了该功能,
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());
}
if语句检查值,并应使用LINQ,WHERE语句过滤列表,
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>
}
但是,当我输入客户名称时,结果不会被过滤,我正在使用SQL Server 2008 R2有没有人遇到这个问题?有没有什么需要让Contains方法工作?
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?
建议是赞赏?
利亚姆
Liam
推荐答案
在排序顺序开关中,使用repository.Customers重新设置cust变量。您应该使用cust变量来应用筛选集上的排序。
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.
switch (sortOrder)
{
case "CustomerName desc":
cust = cust.OrderByDescending(s => s.CustomerName);
break;
这篇关于Asp.Net MVC3添加搜索功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!