how to retain checkbox value in mvc3 webgrid on pa

2019-06-14 01:35发布

问题:

I am using an MVC3 Webgrid to display some data, and have applied server side paging/sorting. I also have a checkbox column in the grid. My problem is that when I change pages, I am losing the selected records. I am able to store the selected row IDs in a session variable, but am unable to retrieve the values from the session and bind to the checkboxes in the Webgrid.

Can someone throw some light on this issue? Please also let me know if there is any other/better approach.

Thanks in advance.

回答1:

Here is a small sample project showing how I've done it. It's based on different answers I've found mostly on Stack Overflow.

The trick is to use @Html.Raw and only emit the checked attribute when the item is selected. Setting checked="false" won't work!

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<Player>
                          {
                              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<String>();

        return View(players);
    }

    [HttpPost]
    public ActionResult Select(bool isChecked, String id)
    {
        var selectList = (List<String>)HttpContext.Session["SelectList"] ?? new List<String>();
        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<CheckboxPaging.Models.Player>

<script type="text/javascript">
    $(function () {
        $(':checkbox').change(function () {
            $.ajax({
                url: '@Url.Action("Select")',
                type: 'POST',
                data: { isChecked: $(this).is(':checked'), id: $(this).val() },
                success: function (result) {
                }
            });
        });
    });
</script>

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

<h2>SCORING LEADERS As of TUE 15 MAY 2012</h2>

@grid.GetHtml(
    tableStyle: "grid",
    headerStyle: "head",
    alternatingRowStyle: "alt",
    columns: grid.Columns(
        grid.Column("Select", format: @<text><input name="Id" type="checkbox" value="@item.Id" @Html.Raw(((List<String>)ViewData["SelectList"]).Contains(@item.Id) ? "checked" : "") /></text>),
        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; }
    }
}