2010-02-24 65 views
0

我對MVC相當陌生。我正在設置一個搜索頁面來搜索數據庫並返回結果。搜索框在我看來是一個Html.BeginForm內,看起來像這樣:ActionResult不會被routelink調用。表單收集的罪魁禍首?

<% using (Html.BeginForm()) 
    { %> 
     <%= Html.TextBox("searchBox", null, new { @id = "searchBox" })%> 
     <div id="searchButtonsDiv"> 
     <input type="submit" value="Search" /> 
     </div> 
    <% } %> 

    //Results are returned in a ul and orgainized 


    //Pagination below 
    <% if (Model.HasPreviousPage) 
     { %> 
     <%= Html.RouteLink("Previous", "SearchResults", new { page = (Model.PageIndex - 1) })%> 
    <% } %> 
    <% if (Model.HasNextPage) 
     { %> 
     <%= Html.RouteLink("Next", "SearchResults", new { formCollection = "", page = (Model.PageIndex + 1) })%> 
    <% } %> 

我使用的FormCollection傳遞給我的控制器看起來像這樣:

[AcceptVerbs(HttpVerbs.Post)] 
    public ActionResult Index(FormCollection formCollection, int? page) 
    { 
     var searchString = formCollection["searchBox"]; 
     var results = resultsRepository.GetResults(); 

     var paginatedResults = new PaginatedList<Driver>(results, page ?? 0, pageSize); 

     return View(paginatedResults); 
    } 

到目前爲止好。當我輸入一個單詞並按下提交按鈕時,索引被調用並且數據庫相應地返回。 ul得到結果填充,並且當pageSize結果多於10(在我的情況下)時,Next鏈接顯示出來。

當我點擊「下一步」時,只會加載默認頁面。沒有分頁或類似的東西。我很確定它與我的Index ActionResult具有FormCollection作爲參數的事實有關。我以爲我讀過的地方只能處理字符串/整數?這裏是MapRoute:

 routes.MapRoute(
      "SearchResults", 
      "Drivers/Index/{formCollection}/{page}", 
      new { controller = "Drivers", action = "Index", formCollection = "", page = "" } 
     ); 

我完全錯過了什麼,或者有沒有辦法處理這個?我知道我可以使用jquery/ajax發送包含在搜索列表框中的字符串,但我不想這樣做,因爲後來我計劃添加複選框作爲過濾搜索的手段等。

我試過幾個不同的方式來設置formCollection的值,包括創建一個新的FormCollection,添加searchBox,以及傳遞字符串等。

+0

當你點擊Next時,它只是從Index actionresult調用一個HttpGet? – 2010-02-24 22:45:10

+0

它調用我沒有參數的其他ActionResult索引。 (公共ActionResult指數(){ 返回查看(); 我認爲它永遠不會被調用,因爲它的FormCollection不能用於routelink。我認爲它必須是一個字符串或int。 } – Darcy 2010-02-25 13:48:20

回答

1

該動作中的FormCollection參數不是問題。這將始終有效。

絕對不是然而,屬於你的路線!只要擺脫這一點,你可能會解決這個問題。表單元素不在URI中,只有URI中的東西應該在路由中。

但是,這不是我怎麼寫動作簽名。我建議:

[AcceptVerbs(HttpVerbs.Post)] 
public ActionResult Index(string searchBox, int? page) 
{ 
    var results = resultsRepository.GetResults(); 

    var paginatedResults = new PaginatedList<Driver>(results, page ?? 0, pageSize); 

    return View(paginatedResults); 
} 

最後:在這種情況下,你不應該從一個POST返回View。這會導致用戶奇怪的行爲;例如,當他們按下刷新時,他們的瀏覽器會警告他們重新提交表單。

您應該:

  1. 使用GET,而不是搜索結果POST
  2. 重定向而不是返回視圖。

我會親自挑選第一個。

+0

嗯,我必須使用POST,因爲Index操作被重載(第一次返回一個視圖,第二次返回相同的視圖,但分頁與搜索結果)。 當你說從路線中刪除它,你的意思所以它看起來是這樣?: routes.MapRoute( 「SearchResult所」, 「驅動器/索引/ {PAGE}」, 新{控制器=「 Drivers「,action =」Index「,page =」「} ); 當我這樣做時,ActionResult Index()會被調用。 (爲了以防萬一,我把它放在所有其他路線上) – Darcy 2010-02-25 16:38:13

+1

'GET' v。'POST' *有*遠期影響,*不應該用於重載決議!無論如何,您只需要一個動作 - 當'searchBox'爲空/空且'page'沒有值時,返回未分頁的結果。如果在修復路由時未調用「索引」,那麼您在此處未提及其他問題。 'FormCollection'應該**永遠不會**在路線中! – 2010-02-25 17:24:52

相關問題