我正在尝试在包含一些数据的页面中实现过滤,该页面显示了三个不同的实体:Branches
,Items
和Categories
,所以我使用了一个视图模型:
public class WarehouseData
{
public IEnumerable<Item> Items { get; set; }
public IEnumerable<Category> Categories { get; set; }
public IEnumerable<Branch> Branches { get; set; }
}
在控制器中:
public ActionResult Index(string sort, string search)
{
var warhouse = new WarehouseData();
warhouse.Items = db.Items.Include(c => c.Categories).ToList();
warhouse.Branches = db.Branches;
ViewBag.Search = search;
warhouse.Branches = db.Branches.ToList();
switch (sort)
{
case "q_asc":
warhouse.Items = warhouse.Items.OrderBy(c => c.Quantity).ToList();
ViewBag.Sort = "q_desc";
break;
case "q_desc":
warhouse.Items = warhouse.Items.OrderByDescending(c => c.Quantity).ToList();
ViewBag.Sort = "q_asc";
break;
default:
warhouse.Items = warhouse.Items.OrderBy(c => c.Name).ToList();
ViewBag.Sort = "q_asc";
break;
}
if (!string.IsNullOrEmpty(search))
{
warhouse.Items = warhouse.Items.Where(i => i.Name.Contains(search)).ToList();
ViewBag.Search = search;
}
return View(warhouse);
}
这是Index
视图:
@model WarehouseManagementMVC.ViewModels.WarehouseData
@{
ViewBag.Title = "Index";
}
<h2 style="display:inline-block">Registered Branches | </h2> @Html.ActionLink("Add New Branch", "Create", controllerName: "Branch")
@foreach (var branch in Model.Branches)
{
<ul>
<li>@Html.ActionLink(branch.Location, "Details", "Branch", routeValues: new { id = branch.Id }, htmlAttributes: null)</li>
</ul>
}
<hr />
<h2>All Items Available</h2>
<div>
@using (@Html.BeginForm("Index", "Warehouse", FormMethod.Get))
{
<input type="text" name="search" value="@ViewBag.Search"/>
<input type="submit" value="Filter" />
}
</div>
<table class="table table-bordered">
<tr>
<th>Product</th>
<th>@Html.ActionLink("Quantity", "Index", new { sort = ViewBag.Sort, search = ViewBag.Search })</th>
<th>Categories</th>
</tr>
@foreach (var item in Model.Items)
{
<tr>
<td>
@Html.ActionLink(item.Name, "Details", "Item", routeValues: new { id = item.Id }, htmlAttributes: null)
</td>
<td>
<span>@item.Quantity</span>
</td>
<td>
@{foreach (var cat in item.Categories)
{
@cat.Name <br />
}
}
</td>
</tr>
}
</table>
但是当我搜索时,结果总是空列表,为什么?
答案 0 :(得分:0)
这里只有两件事会导致Items
为空:
这些项目都没有包含搜索字词的Name
值。特别建议Contains
区分大小写。因此,如果名称为Foo
并且您搜索了foo
,那么它将与不匹配。如果您想进行不区分大小写的搜索,那么在比较之前,您应该将Name
和search
同时转换为小写或大写:
Where(m => m.Name.ToLower().Contains(search.ToLower()))
我们在这里的时候。理想情况下,搜索应在数据库级别进行筛选。目前,您正在选择数据库中的所有项目,然后在内存中过滤它们,这是非常低效的。只要您在操作的第二行中调用ToList()
,就会发送查询,但您必须这样做才能设置warhouse.Items
。相反,您应该将项目存储在临时变量中,即IQueryable items = db.Items.Include(c => c.Categories);
,并对其进行所有条件排序和过滤。然后,最后设置warhouse.Items = items.ToList();
。
答案 1 :(得分:0)
我发现搜索区分大小写,这解决了它:
if (!string.IsNullOrEmpty(search))
{
warhouse.Items = warhouse.Items.Where(i => i.Name.ToLower().Contains(search.ToLower())).ToList();
ViewBag.Search = search;
}
如果您对该代码有其他建议,我感谢分享。