我有這樣的動作方法:如何在搜索時保存查詢值? ASP.NET MVC
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Search(String filter, String value, Int32? page) {
var set = new List<Employee>();
switch(filter) {
case "by-name": {
set = this.repository.Get(
e => (e.LastName + " " + e.FirstName + " " + e.MiddleName) == value
).ToList();
break;
}
case "by-empn": {
set = this.repository.Get(
e => e.EmployeeNumber == value
).ToList();
break;
}
default: return RedirectToAction("Search", "Employee");
}
ViewBag.SearchedEmployees = set.Count();
return View(set.ToPagedList(page ?? 1, PageSize));
}
搜索視圖是這樣的:
@if(Model.Count > 0) {
foreach(var item in Model) {
Html.RenderPartial("Employee.Card", item);
}
@Html.PagedListPager(
Model,
page => Url.Action("Search", new { page = page }),
new PagedListRenderOptions {
LinkToFirstPageFormat = "<< Beginning",
LinkToPreviousPageFormat = "< Back",
LinkToNextPageFormat = "Forth >",
LinkToLastPageFormat = "End >>"
}
)
}
搜索形式被呈現爲一個局部視圖:
@using(Html.BeginForm("Search", "Employee", FormMethod.Get, new { @class = "search-form" }))
{
<p>
@Html.TextBox("value")
</p>
<p>
@Html.RadioButton("filter", "by-name", true) By name <br/>
@Html.RadioButton("filter", "by-empn") By empn <br/>
</p>
<p>
<input type="image" src="@Url.Content("~/Content/Images/Search.png")" />
</p>
}
問題:我有N
頁面鏈接。當我嘗試去第二頁時,我面對無限循環的重定向。這就是我實施我的行動的方式 - 默認情況下被解僱。所以filter/value
的值是null
上的第二個動作調用?爲什麼? 如何重構我的搜索行爲?
另外我應該如何配置這樣的行動路線?
謝謝!
編輯
所以應當對搜索行動的樣子路線:
routes.MapRoute(
null,
"{controller}/{action}/Page{page}/filter{filter}/val{value}",
new { controller = "Employee", action = "Search" }
);
?
EDIT 2
因此,有可能在下一個寫:
page => Url.Action("Search", new { filter = ViewBag.SearchFilter, value = ViewBag.SearchValue, page = page }),
和控制器內:
public ActionResult Search(String filter, String value, Int32? page) {
ViewBag.SearchFilter = filter;
ViewBag.SearchValue = value;
// ...
}
這是正確的?
1)請看我的編輯; 2)我正在使用Troy Goode的分頁列表。我寫過這樣的東西(編輯2)。 – lexeme
是的,這似乎是一個很好的方式來自己生成網址幷包含2個參數。我會使用一個強類型的視圖模型而不是'ViewBag',但是如果你感覺更舒服,繼續使用它。 –
酷!我還提到,當我做出第一個搜索請求時,我得到了這樣的URL:http:// localhost:51126/Employee/Search/Page2?value =%D0%A6%D0%A2%D0%94&filter = by-dept&x = 24 Y = 13'。我不明白'x'和'y'來自哪裏?我如何形成我的路線進行相應的操作? – lexeme