Asp.net-Mvc-3

Asp.net Mvc3 webgrid 和分頁

  • March 20, 2013

我正在嘗試學習 Asp.net mvc。我知道它與形式不同,我可能需要改變我的思維方式。我的問題是關於 webgrid 。當我將 webgrid 添加到我的頁面並使用 Post 點擊搜尋按鈕時,它會使用尋呼機等呈現表格。但是尋呼機上的連結沒有發布表單,它們只是連結,我失去了所有表單的數據。

控制器有兩種索引方法,一種用於獲取,另一種用於發布。為了讓我什麼都不做,我只是在這種情況下創建新的視圖模型搜尋類並將其設置為視圖。對於我的發布方法,我抓住我的視圖模型進行搜尋並將填充的視圖模型設置為查看。

問題:webgrid 將尋呼機呈現為連結,因此它將進入索引以獲取但由於它不是發布請求,因此我沒有填寫任何表單欄位,並且我的搜尋不會提供完全相同的結果集。

也許範常式式碼可以更好地解釋它。

看法:

<form action="" method="post">

Esas no : @Html.TextBoxFor(x=>x.Name)
Yil : @Html.TextBoxFor(x=>x.Year)

<input type="submit" value="Search" />

<hr />
@ViewBag.Message
<hr />

@{ var grid = new WebGrid(Model.Results,rowsPerPage:5);}

@grid.GetHtml(tableStyle:"table",htmlAttributes:new {id="tbl"} )

</form>

這是我的控制器:搜尋發生在 Index Post 方法中,它只有我的 viewmodel 類。

   private ISearchContext _sc;

   public  MyController(ISearchContext sc)
   {
       _dc = dc;
   }

   //
   // GET: /Dava/

   public ActionResult Index()
   {
       var search = new Search();
       ViewBag.Message = "";
       return View(search);
   }

   [HttpPost]
   public ActionResult Index(Search search)
   {

       Search sres = _dc.SearchFromRepository(search);
       ViewBag.Message = String.Format("Count:{0} ",sres.Results.Count);
       return View(sres);
   }

搜尋模型類是這樣的:

public class Search
{
   public int Year { get; set; }
   public string Name { get; set; }


   public IList<Item> Results { get; set; }

   public Search()
   {
       Results = new List<Item>();
   }
}

解決此問題的一種方法是使用 javascript 並訂閱任何尋呼機連結的點擊事件,然後獲取所需頁面的值,將其註入表單上的隱藏欄位並將表單送出到伺服器,以便其他兩個值也被發送。

因此,首先Page在視圖模型上添加一個可為空的整數屬性,Search並將相應的隱藏欄位添加到包含所選頁碼的表單中:

@Html.HiddenFor(x => x.Page, new { id = "page" })

然後,您只需要在頁面中添加一個小的 javascript 片段即可訂閱尋呼機連結的 .click 事件:

$(function () {
   $('tfoot a').click(function () {
       // when the user clicks on any of the pager links
       // try to extract the page number from the link and
       // set the value of the hidden field
       var page = this.href.match(/page=([0-9])+/)[1];
       $('#page').val(page);

       // submit the form so that the POST action is invoked
       // passing along the search criteria (Name and Year) along
       // with the page hidden field value to the Index action
       $('form').submit();

       // cancel the default action of the link which is to simply redirect
       // to the Index action using a GET verb.
       return false;
   });
});

引用自:https://stackoverflow.com/questions/6343962