如何在分页上保留mvc3 webgrid中的复选框值

我使用MVC3 Webgrid显示一些数据,并已应用服务器端分页/排序。 我在网格中也有一个复选框列。 我的问题是,当我更改页面时,我正在丢失所选记录。 我能够将选定的行ID存储在会话变量中,但无法从会话中检索值并绑定到Webgrid中的复选框。

有人可以对这个问题有所了解吗? 如果有任何其他/更好的方法,也请告诉我。

提前致谢。

这是一个小样本项目,展示了我是如何做到的。 它基于我在Stack Overflow上发现的不同答案。

诀窍是使用@Html.Raw并仅在checked项目时发出checked属性。 设置checked="false"将无效!

HomeController.cs:

 using System; using System.Collections.Generic; using System.Web.Mvc; using CheckboxPaging.Models; namespace CheckboxPaging.Controllers { public class HomeController : Controller { public ActionResult Index() { var players = new List { new Player {Id = "NOR41", Rank = 1, Name = "THORESEN Patrick", Country = "NOR", Points = 16}, new Player {Id = "RUS11", Rank = 2, Name = "MALKIN Yevgeni", Country = "RUS", Points = 14}, new Player {Id = "SWE40", Rank = 3, Name = "ZETTERBERG Henrik", Country = "SWE", Points = 13}, new Player {Id = "USA67", Rank = 4, Name = "PACIORETTY Max", Country = "USA", Points = 12}, new Player {Id = "SWE21", Rank = 5, Name = "ERIKSSON Loui", Country = "SWE", Points = 11}, new Player {Id = "NOR19", Rank = 6, Name = "SKRODER Per-Age", Country = "NOR", Points = 11}, new Player {Id = "CAN2", Rank = 7, Name = "KEITH Duncan", Country = "CAN", Points = 11}, new Player {Id = "FIN51", Rank = 8, Name = "FILPPULA Valtteri", Country = "FIN", Points = 9}, new Player {Id = "CAN20", Rank = 8, Name = "TAVARES John", Country = "CAN", Points = 9}, new Player {Id = "USA26", Rank = 10,Name = "STASTNY Paul", Country = "USA", Points = 9} }; ViewData["SelectList"] = HttpContext.Session["SelectList"] ?? new List(); return View(players); } [HttpPost] public ActionResult Select(bool isChecked, String id) { var selectList = (List)HttpContext.Session["SelectList"] ?? new List(); if(isChecked && !selectList.Contains(id)) { selectList.Add(id); } else if(!isChecked && selectList.Contains(id)) { selectList.RemoveAll(s => s == id); } HttpContext.Session["SelectList"] = selectList; return Content("OK"); } public ActionResult About() { return View(); } } } 

Index.cshtml:

 @model IEnumerable  @{ var grid = new WebGrid(source: Model, defaultSort: "Rank", canSort: true, rowsPerPage: 5 ); } 

SCORING LEADERS As of TUE 15 MAY 2012

@grid.GetHtml( tableStyle: "grid", headerStyle: "head", alternatingRowStyle: "alt", columns: grid.Columns( grid.Column("Select", format: @)ViewData["SelectList"]).Contains(@item.Id) ? "checked" : "") />), grid.Column("Rank", "Rank"), grid.Column("Name", "Name"), grid.Column("Country", "Country"), grid.Column("Points", "Points") ) )

Player.cs:

 using System; namespace CheckboxPaging.Models { public class Player { public String Id { get; set; } public int Rank { get; set; } public String Name { get; set; } public String Country { get; set; } public int Points { get; set; } } }