使用Pagedlist NuGet软件包通过分页保持复选框处于选中状态

时间:2019-06-28 22:28:36

标签: c# asp.net-mvc

我有一个网格,每行都有一个复选框,并且有分页(Pagedlist nuget程序包)。假设我选择行号(1,3)并转到第2页,然后再返回到第1页时,我之前丢失了选择(1,3)。

我曾尝试将id像本地存储一样保存在客户端,但是单击另一页后这些值会丢失。

public class MerchantModel
{
    public int AppId { get; set; }
    public string Name { get; set; }
    public bool IsSelected { get; set; }
}

 public class MerchantViewModel
{
    public IPagedList<MerchantModel> Merchants { get; set; }
}

public ActionResult Index(int? page)
    {
        var merchant1 = new MerchantModel
        {
            AppId = 1,
            Name = "Bob"
        };

        var merchant2 = new MerchantModel
        {
            AppId = 2,
            Name = "Ted"
        };

        List<MerchantModel> list = new List<MerchantModel>();
        list.Add(merchant1);
        list.Add(merchant2);

        var pageNumber = page ?? 1;

        var model = new MerchantViewModel
        {
            Merchants = list.ToPagedList(pageNumber, 1)
        };

        return View(model);
    }

这是索引视图

<script type="text/javascript">

    var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {};

    $(function () {

        $(".chkTest").each(function () {

            if ($.inArray($(this).val(), checkboxValues) > -1) {
                $(this).attr("checked", "checked");
            }
        });

        $(".chkTest").change(function () {
            checkboxValues[this.id] = this.checked;
        });
        localStorage.setItem("checkboxValues", JSON.stringify(checkboxValues));
    });

</script>
         <table id="Test">
            @for (int i = 0; i < Model.Merchants.Count; i++)
            {
                <tr>
                    <td>
                        @Html.CheckBoxFor(x => x.Merchants[i].IsSelected, 
                            new {@class = "chkTest", @Value = Model.Merchants[i].AppId})
                    </td>
                    <td>
                        @Html.HiddenFor(x => x.Merchants[i].AppId)
                        @Model.Merchants[i].AppId
                    </td>
                    <td>
                        @Html.HiddenFor(x => x.Merchants[i].Name)
                        @Model.Merchants[i].Name
                    </td>
                </tr>
            }

        </table>
        @Html.PagedListPager(
            Model.Merchants,
            page => Url.Action("Index", new {page = page}),
            PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(
                new AjaxOptions()
                {
                    HttpMethod = "GET",
                    UpdateTargetId = "Test"
                })
            )
                  <button type="submit">Submit</button>

       I need some server-side or client-side solution to solve this problem.

0 个答案:

没有答案