2012-05-14 22 views
0

我有這樣的動作方法:如何在搜索時保存查詢值? 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

因此,第二個動作調用中的過濾器/值的值爲空?爲什麼?

因爲它們相應的輸入字段是在一個單獨的表單中,並且永遠不會發送到服務器。

你似乎在使用一些自定義Html.PagedListPager幫助程序(你沒有顯示的代碼),但我猜這個幫助程序生成頁面鏈接作爲錨點,它根本沒有考慮任何當前查詢字符串或生成這些鏈接時發佈的值。因此,您的分頁鏈接的href看起來像這樣/SomeController/Search?page=5而不是正確的,它會考慮那些參數/SomeController/Search?page=5&filter=somefilter&value=somevalue

您現在可以輕鬆理解爲什麼控制器操作中的參數filtervalue始終爲空。這是因爲當你點擊分頁鏈接時,你永遠不會將它們發送到服務器。

因此,爲了解決此問題,您可以修改您正在使用的自定義HTML幫助程序,以生成分頁鏈接以包含這些附加參數。或者,也許助手允許你傳遞額外的參數?如果這是您正在使用的第三方插件,請檢查文檔。

+0

1)請看我的編輯; 2)我正在使用Troy Goode的分頁列表。我寫過這樣的東西(編輯2)。 – lexeme

+0

是的,這似乎是一個很好的方式來自己生成網址幷包含2個參數。我會使用一個強類型的視圖模型而不是'ViewBag',但是如果你感覺更舒服,繼續使用它。 –

+0

酷!我還提到,當我做出第一個搜索請求時,我得到了這樣的URL:http:// localhost:51126/Employee/Search/Page2?value =%D0%A6%D0%A2%D0%94&filter = by-dept&x = 24 Y = 13'。我不明白'x'和'y'來自哪裏?我如何形成我的路線進行相應的操作? – lexeme