简体   繁体   中英

load jqGrid on button click but it fails on second time

I'm using jqGrid to display data from database. There are 2 textboxes to input the criteria. After inputting the criteria and clicking the Show button, jqGrid is shown to the page.

The second time I clicked the Show button with a different set of criteria entered nothing happens. It still shows data from the first click. How do I solve this?

View:

@section styles {
    <link href="~/Content/themes/redmond/jquery-ui.css" rel="stylesheet" />
    <link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />
}

<h2>Index</h2>

<p class="form-inline">
    Ext: <input type="text" class="form-control" id="extUsed" />
    Date: <input type="text" class="form-control" id="startOfCall" readonly="readonly" />
    <button class="btn btn-primary" id="btnShow">Show</button>
</p>

<table id="grid"></table>
<div id="pager"></div>

@section scripts {
    <script src="~/Scripts/i18n/grid.locale-en.js"></script>
    <script src="~/Scripts/jquery.jqGrid.min.js"></script>
    <script>
        var firstClick = true;
        $(function () {
            $("#startOfCall").datepicker();

            $("#btnShow").click(function (e) {
                e.preventDefault();

                if (!firstClick) {
                    $("#grid").trigger("reloadGrid");
                } else {

                    $("#grid").jqGrid({
                        mtype: "GET",
                        url: "@Url.Content("~/CallTransaction/GetCallTransactionList")",
                        datatype: "json",
                        colNames: ["Ext Used", "Start of Call", "Destination Number"],
                        colModel: [
                            { name: "ExtUsed", index: "ExtUsed" },
                            { name: "StartOfCall", index: "StartOfCall", formatter: "date", formatoptions: { srcformat: 'd/m/Y', newformat: 'd/m/Y' } },
                            { name: "DestinationNumber", index: "DestinationNumber" }
                        ],
                        postData: {
                            "CallTransaction.ExtUsed": $("#extUsed").val(),
                            "CallTransaction.StartOfCall": $("#startOfCall").val()
                        },
                        pager: jQuery("#pager"),
                        rowNum: 10,
                        rowList: [10, 25, 50],
                        height: "100%",
                        caption: "Call Transaction",
                        autowidth: true,
                        //sortname: "ExtUsed",
                        sortable: true,
                        viewrecords: true,
                        emptyrecords: "No records to display",
                    });
                    $("#grid").jqGrid('navGrid', '#pager', { edit: false, add: false, del: false, search: false });
                }
                firstClick = false;
            });
        });
    </script>
}

Controller:

public JsonResult GetCallTransactionList(CallTransaction callTransaction, string sidx, string sord, int page, int rows)
{
    int pageIndex = page - 1;
    int pageSize = rows;
    var callTransactionResult = db.Search(callTransaction);
    int totalRecords = callTransactionResult.Count();
    var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
    if (sord.ToUpper() == "DESC")
    {
        callTransactionResult = callTransactionResult.OrderByDescending(ct => ct.ExtUsed).ToList();
        callTransactionResult = callTransactionResult.Skip(pageIndex * pageSize).Take(pageSize).ToList();
    }
    else
    {
        callTransactionResult = callTransactionResult.OrderBy(ct => ct.ExtUsed).ToList();
        callTransactionResult = callTransactionResult.Skip(pageIndex * pageSize).Take(pageSize).ToList();
    }
    var jsonData = new
    {
        total = totalPages,
        page,
        records = totalRecords,
        rows = callTransactionResult
    };
    return Json(jsonData, JsonRequestBehavior.AllowGet);
}

It's important to understand that the current code set one value of postData during creating the grid. The value of postData parameter will be object with properties evaluated at the moment of creating of the grid.

To fix the code you need use function as the value of postData properties:

postData: {
    "CallTransaction.ExtUsed": function () { return $("#extUsed").val(); },
    "CallTransaction.StartOfCall": function () { return $("#startOfCall").val(); }
}

See the answer for more details. For understanding: jqGrid uses jQuery.ajax internally and jQuery.ajax uses jQuery.param helper function to process the data parameter (construction using postData ) and jQuery.param execute functions if it is the properties of data ( postData ).

Additionally I would strictly recommend you to use gridview: true option in all your grids (see the answer ), add autoencode: true to interpret the input data as the data instead of HTML fragments (it's the default behavior) and to use pager: "#pager" instead of pager: jQuery("#pager") .

I recommend you to remove all index properties from colModel and to consider to include additional id property in the data returned from the server with an unique values which come from the database. If some column of the grid already contains the unique value you can add key: true property to the definition of the corresponding column. The reason of such changes is easy to understand if you know that jqGrid have to assign id attribute to every row of grid. The value of id attribute must be unique. The value, used as rowid in the documentation, will be used in the most callbacks of jqGrid to identify the row. The same value will be send to the server if you will implement editing of data later. If you don't specify any rowid in the input data jqGrid have to assign some other value to id . The default value will be 1,2,3... On the other side if you load the data from the database you have native ids of the rows. The usage of the native ids can "simplify your live" in the future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM