【问题标题】:Enable pager in jQgrid if the grid has loadonce: false如果网格有 loadonce,则在 jQgrid 中启用寻呼机:false
【发布时间】:2014-04-26 20:53:51
【问题描述】:

我用 jQgrid 创建了一个新的列表数据,并在初始网格数据加载后用两个日期值过滤数据。请在下面查看我的代码。

.cshtml

@{
ViewBag.Title = "AdvertiseList";
Layout = "~/Views/Shared/_LayoutAdmin.cshtml";
}
<style type="text/css">
 .img_div {
    width: 13%;
 }
 </style>
 <script src="~/Scripts/jquery-1.9.1.js"></script>
 <script src="~/Scripts/jquery-ui-1.10.4.js"></script>
 <script src="~/Scripts/jquery.jqGrid.src.js"></script>
 <link href="~/jquery-ui-1.10.4.custom/css/ui-darkness/jquery-ui-1.10.4.custom.css"   rel="stylesheet" />
 <script src="~/Scripts/i18n/grid.locale-pt.js"></script>
 <script src="~/jquery-ui-1.10.4.custom/development-bundle/ui/i18n/jquery.ui.datepicker-pt.js"></script>
 <script type="text/javascript">
jQuery.jgrid.no_legacy_api = true;
</script>
<link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />
<script src="~/dist/JS/bootstrap-tooltip.js"></script>
<style>
.well {
    min-height: 500px;
    height: auto;
    margin-top: 40px;
}
</style>
<div class="well">
<h4 style="color: black;">Lista Anuncie</h4>
<br clear="all" />
<div class="form-inline">
    <div class="form-group">
        <input type="text" class="form-control" id="fromdate" placeholder="De Data">
    </div>
    <div class="form-group">
        <input type="text" class="form-control" id="todate" placeholder="Para Data">
    </div>
    <button id="btnSearch" type="submit" class="btn btn-default">Search</button>
</div>

<br clear="all" />
<div><b>Total de usuários: @ViewBag.Advertisecount</b></div>
<table id="jQGridDemo">
</table>
<div id="jQGridDemoPager">
</div>
<table id="search"></table>
<div id="filter"></div>
<script type="text/javascript">

    $(document).ready(function () {
        $("#fromdate").tooltip({ 'trigger': 'focus', 'title': 'De Data' });
        $("#todate").tooltip({ 'trigger': 'focus', 'title': 'Para Data' });
    });
    jQuery("#jQGridDemo").jqGrid({
        url: '@Url.Action("FillUsers", "Admin")',
        postData: {
            fromDate: function () {
                return $("#fromdate").val();
            },
            toDate: function () {
                return $("#todate").val();
            }
        },
        datatype: "json",
        mtype: "POST",
        colNames: ["Id", "Nome", "Email", "Senha", "Descrição", "Telefone",               "Endereço", "Data", "View Details"],
        colModel: [
             { name: "Id", width: 100, key: true, formatter: "integer", sorttype: "integer", hidden: true },
            { name: "Name", width: 200, sortable: true, editable: true, editrules: { required: true } },
            { name: "Email", width: 250, sortable: true, editable: true, editrules: { required: true } },
            { name: "Password", width: 200, sortable: true, editable: true, editrules: { required: true }, hidden: true },
            { name: "Description", width: 200, sortable: true, editable: true, editrules: { required: true }, hidden: true },
            { name: "Phone", width: 200, sortable: true, editable: true, editrules: { required: true }, hidden: true },
            { name: "Address", width: 350, sortable: true, editable: true, editrules: { required: true } },
            { name: "Date", width: 150, align: "center", formatter: "date", formatoptions: { srcformat: "ISO8601Long", newformat: "d-m-Y" }, sorttype: "date", datefmt: 'dd-mm-yy' },
            { name: "Edit",width:100,align: "center",editable: true,formatter:                    BuildAdvertiseUrl }
        ],
        rowNum: 500,
        gridview: true,
        autoencode: true,
        loadonce: false,
        height: "auto",
        rownumbers: true,
        prmNames: { id: "Id" },
        rowList: [5, 10, 20, 30],
        pager: '#jQGridDemoPager',
        emptyrecords: "Não há registros para exibir",
        sortname: 'id',
        sortorder: "asc",
        viewrecords: true,
        caption: "Lista de Usuários",
        width: 1000
    });
    jQuery("#jQGridDemo").jqGrid('navGrid', '#jQGridDemoPager',
    {
        del: false,
        edit: false,
        add: false,
        search: false
    },
    {//EDIT
    },
    {//ADD
    },
    {//DELETE
    },
    {//SEARCH 
    });

    $("#fromdate").datepicker({ dateFormat: 'dd-mm-yy' });
    $("#todate").datepicker({ dateFormat: 'dd-mm-yy' });

    $("#btnSearch").click(function () {
        $("#jQGridDemo").trigger("reloadGrid", [{ page: 1 }]);
    });

    function DeleteAdvertisementPopup(id) {

        $("#dialog-message").dialog({
            modal: true,
            buttons: {
                Ok: function () {

                    var url = "@Url.Action("DeleteAdd", "Admin")"

                    $.ajax({
                        type: "POST",
                        url: url,
                        data: "{ Id : " + id + " }",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (data) {
                            $("#jQGridDemo").trigger("reloadGrid", [{ current: true }]);
                        }
                    });

                    $(this).dialog("close");
                },
                Cancelar: function () {
                    $(this).dialog("close");
                }
            }
        });
    }

    function BuildAdvertiseUrl(cellvalue, options, rowObject) {
        var url = "/Admin/EditAdvertise?Id=" + rowObject[0];
        var advertiseId = rowObject[0];
        return "<a href=" + url + "><img src='../Images/viewdetails.png'/></a><a onclick=\"javascript:DeleteAdvertisementPopup(" + advertiseId + ");\">&nbsp;<img width='16' height='16' src='../Images/button_delete.png'/></a>";
    }
</script>
</div>
@*-------Dialog message for confirmation to delete the advertisement-------------------*@
<div id="dialog-message" style="font-size: 13px;" title="Excluir Anuncie">
<p>
    Você quer apagar este anúncio?
</p>
</div>
@*-------------Endhtml-----------------*@

控制器中的操作

    public ActionResult AdvertiseList()
    {
        Session["AdvertiserId"] = null;
        if (Session["admin"] == null)
            return RedirectToAction("SignUpAdvertiser", "Home");
        else
        {
            using (DBLockScreenAppEntities db = new DBLockScreenAppEntities())
            {
                var user = db.Advertisers.Count();
                ViewBag.Advertisecount = user;
            }
        }

        return View();
    }

    public JsonResult FillUsers(string fromDate, string toDate, string sidx, string sord, int page, int rows)
    {
        var users = new List<Advertiser>();
        using (DBLockScreenAppEntities db = new DBLockScreenAppEntities())
        {
            if (!string.IsNullOrEmpty(fromDate) && !string.IsNullOrEmpty(toDate))
            {
                DateTime FromDate = new DateTime(Convert.ToInt32(fromDate.Split('-')[2]), Convert.ToInt32(fromDate.Split('-')[1]), Convert.ToInt32(fromDate.Split('-')[0]), 0, 0, 0);
                DateTime ToDate = new DateTime(Convert.ToInt32(toDate.Split('-')[2]), Convert.ToInt32(toDate.Split('-')[1]), Convert.ToInt32(toDate.Split('-')[0]), 23, 59, 59);

                users = db.Advertisers.Where(e => e.Date >= FromDate && e.Date <= ToDate).OrderByDescending(e => e.Date).ToList();
            }
            else
            {
                users = db.Advertisers.OrderByDescending(e => e.Date).ToList();
            }
        }
        return Json((
                from user in users
                select new[]{
                    user.Id.ToString(System.Globalization.CultureInfo.InvariantCulture),
                    user.Name,
                    user.Email,
                    user.Password,
                    user.Description,
                    user.Phone,
                    user.Address,
                    user.Date == null ? "": ((DateTime) user.Date).ToString("o")
                }
            ).ToArray(), JsonRequestBehavior.AllowGet);
    }

请看下面我的截图

我设置了loadonce: falsedatatype: "json",以重新加载带有对应日期的网格。但现在我想在我的网格中添加一个寻呼机。我找到了一些配置脚本来执行此操作。您能否建议一种启用寻呼机的方法。

【问题讨论】:

  • 您需要在网格中显示多少行? (10, 100, 1000, 10000, 100000, ...)? loadonce: falseloadonce: true 之间的最佳选择取决于可以显示的最大行数。
  • 非常感谢您的宝贵回复。我想在每页显示 50 行。
  • 所有页面中总共有多少行可以在网格中?
  • 总记录1000条,以后会增加更多记录。
  • 你能不能给点建议.....

标签: c# asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 jqgrid


【解决方案1】:

如果您真的需要 遵循loadonce: false 方案,您将必须实现服务器端 数据分页。您需要使用 jqGrid 发送到服务器的 pagerows 参数。服务器代码也应该实现数据的服务器端排序。所以你必须使用sidxsord 选项。此外,您必须更改从服务器返回的数据格式。您应该返回对象而不是项目数组

{
    total,   // total number of pages
    page,    // 1-based number of returned page
    records, // total number of rows in all pages
    rows     // the array of rows for the requested page only
}

因此,您需要使用类似

的东西,而不是返回users
var pageOfUsers = users.Skip (
    "it." + sidx + " " + sord,
    "@skip",
    new ObjectParameter ("skip", (page - 1) * rows)
).Top ("@limit", new ObjectParameter ("limit", rows));

然后返回

var totalRecords = users.Count(); // total number of users
return Json(new {
    total = (totalRecords + rows - 1) / rows,
    page,
    records = totalRecords,
    rows = (from item in pageOfUsers
            select new[] {
                user.Id.ToString(System.Globalization.CultureInfo.InvariantCulture),
                user.Name,
                user.Email,
                user.Password,
                user.Description,
                user.Phone,
                user.Address,
                user.Date == null ? "": ((DateTime) user.Date).ToString("o")
            }).ToList()
}, JsonRequestBehavior.AllowGet);

另一方面,我建议您考虑将 loadonce: true 场景与 local paging 结合使用。在这种情况下,您根本不会更改您的服务器代码,只需设置rowNum: 50loadonce: true。如果加载 1000 甚至 10000 行,它通常会足够快。如果您使用rowNum: 50(显示50 行),那么网格将仅显示从服务器返回的所有1000 行中的前50 行。用户可以使用 local 分页或排序(通过单击某些列标题)。此外,您可以添加filterToolbar 的调用,允许用户过滤以前加载的数据。您还可以使用 jqGrid 的search: true 选项来允许用户对加载的数据进行非常复杂的查询(您可以在代码的//SEARCH 部分中使用multipleSearch:truemultipleGroup:true searching option)。在本地数据总量为 1000 行的情况下,本地排序、本地分页和本地过滤/搜索数据的响应时间将是完美的。这样用户就可以真正的分析返回的数据,你不需要编写任何长代码。

您要做的是将datatype 休息到"json" 内部$("#btnSearch").clickbeforeRefresh 内部(参见the answer):

$("#btnSearch").click(function () {
    $("#jQGridDemo").jqGrid("setGridParam", {datatype: "json"})
        .trigger("reloadGrid", [{ page: 1 }]);
});

通过单击按钮"#btnSearch" 或网格的刷新按钮,您将基于"#fromdate""#todate"从服务器重新加载数据。所有其他操作将在本地使用之前加载的数据完成。

【讨论】:

  • 奥列格 非常感谢。我会听从你的指示。
  • @RageshPuthiyedath:不客气!如果您更喜欢使用服务器端 分页、排序,尤其是过滤/搜索the old answer 可以为您提供一些可能有用的代码示例。一般来说,我建议您最好使用 client side (loadonce: true) 分页、排序和搜索/过滤。从用户的角度来看,Web 端将更加负责,您将需要编写更少的代码。
  • 非常感谢奥列格。上帝保佑你。
  • @RageshPuthiyedath:不客气!对我来说,您最后选择了哪种方式很有趣:1)从服务器返回所有数据以及在"setGridParam", {datatype: "json"} 之前使用loadonce: truereloadGrid 或2)使用.Skip.Top 的服务器端分页并修改了返回数据的格式?
猜你喜欢
  • 2011-05-10
  • 2011-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-30
  • 1970-01-01
  • 2011-04-12
相关资源
最近更新 更多