我有一个基本的MVC应用程序,我正在尝试实现一些搜索功能。当我输入数据并单击"搜索"时,URL会按预期更新,但是索引页面仍然返回所有结果,而不是过滤结果。我在下面有我的代码,想知道是否有人可以指出为什么是这种情况?我不相信我需要单独的帖子方法,根据我过去所做的事情,但是我仍然是新手,因为我仍然是新手。谢谢。
index.cshtml:
<p>
@Html.ActionLink("Create New Employee", "Create")
</p>
<form asp-action="Index" method="get">
<div class="form-actions no-color">
<p>
Find by name: <input type="text" name="searchString" value="@ViewBag.CurrentFilter" />
<input type="submit" value="Search" class="btn btn-default" /> |
<a asp-action="Index">Back to List</a>
</p>
</div>
</form>
控制器:
public ActionResult Index(string searchString)
{
var person = from p in db.Person
select p;
ViewBag.CurrentFilter = searchString;
if (!String.IsNullOrEmpty(searchString))
{
person = person.Where(s => s.LastName.Contains(searchString));
//|| p.FirstName.Contains(searchString));
}
return View(db.Person.ToList());
}
单击搜索时返回的URL:
http://localhost:9999/Person/Index?searchString=smith
,因为您将错误的结果返回到视图,这要求将所有行从人表返回并传递给查看,因此请从:
更改最后一行return View(db.Person.ToList());
to:
return View(person.ToList());
使其返回过滤结果设置为视图。