对表进行排序/搜索不起作用
本文关键字:搜索 不起作用 排序 | 更新日期: 2023-09-27 18:34:14
>排序和搜索机制在我们的.NET MVC项目中不起作用。我完成了控制器和视图的编码,除了排序和搜索之外,一切都很好。
控制器:
public ActionResult Index(string sortOrder, string searchString)
{
ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
ViewBag.CustomerNameSortParm = String.IsNullOrEmpty(sortOrder) ? "cust_name_desc" : "";
ViewBag.LastSucceedOnSortParm = sortOrder == "Date" ? "succeed_date_desc" : "Date";
var farms = from f in db.Farms
select f;
if (!String.IsNullOrEmpty(searchString))
{
farms = farms.Where(s => s.LicenseKey.ToUpper().Contains(searchString.ToUpper()) || s.Name.ToUpper().Contains(searchString.ToUpper()));
}
switch (sortOrder)
{
case "name_desc":
farms = farms.OrderByDescending(f => f.Name);
break;
case "cust_name_desc":
farms = farms.OrderByDescending(f => f.CustomerName);
break;
case "succeed_date_desc":
farms = farms.OrderBy(f => f.LastSucceedOn);
break;
}
return View(db.Farms.ToList());
}
视图:
@using (Html.BeginForm())
{
<p>
Search: @Html.TextBox("SearchString")
<input type="submit" value="Search" />
</p>
}
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.LicenseKey)
</th>
<th>
@*@Html.DisplayNameFor(model => model.Name)*@
@Html.ActionLink("Name", "Index", new { sortOrder = ViewBag.NameSortParm })
</th>
<th>
@*@Html.DisplayNameFor(model => model.CustomerName)*@
@Html.ActionLink("CustomerName", "Index", new { sortOrder = ViewBag.CustomerNameSortParm })
</th>
<th>
@Html.DisplayNameFor(model => model.FarmDate)
</th>
<th>
@*@Html.DisplayNameFor(model => model.LastSucceedOn)*@
@Html.ActionLink("LastSucceedOn", "Index", new { sortOrder = ViewBag.LastSucceedOnSortParm })
</th>
<th></th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.ActionLink(item.LicenseKey, "FarmDetails", "Farm", new { id = item.Id }, null)
</td>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.CustomerName)
</td>
<td>
@Html.DisplayFor(modelItem => item.FarmDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.LastSucceedOn)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.Id })
</td>
<td>
@Html.ActionLink("Settings", "Index", "Settings")
</td>
</tr>
}
</table>
我的代码的哪一部分是错误的?一定在某处有一个简单的错误,但我看不到它。谢谢。
我理解db。农场是完整列表。对该列表进行排序和筛选,并将结果保存在本地服务器场变量中。但将未过滤的数据库返回到客户端。农场。只需将其替换为农场,它应该可以工作
return View(farms.ToList());