JQGrid 'reloadGrid' 不会在 ASP.Net MVC 中触发

JQGrid 'reloadGrid' does not trigger in ASP.Net MVC

请注意,对于 Stack Overflow 上已有的各种问题,我已经尝试了几乎所有可以找到的解决方案,但没有任何解决方案对我有用。

所以请不要将此标记为重复投票或反对票。请协助解决以下情况:

我有一个 JQGrid,它最初从一些 table (SQL Db) 加载所有数据。有一个选项可以通过从下拉列表中选择值来过滤数据。更改下拉列表会触发对服务器的 ajax 调用,该服务器 returns 从服务器(MVC 控制器)过滤数据。然而,当数据从控制器返回时,数据是正确的,但它没有反映在 JQGrid 中。我已经尝试了所有不同的方法来触发 JQGrid 的重新加载,但没有任何效果。

剃须刀View/JQuery代码:

@model IEnumerable<OSMPortalV2.Models.NetworkCertsATC_SP>

<!-- widget content -->
<div class="widget-body fuelux">
    <form name="networkCertficates">
        <!-- widget div-->
        @{
            List<SelectListItem> ddlistItems = new List<SelectListItem>();
            ddlistItems.Add(new SelectListItem { Text = "All Certificates", Value = "All", Selected = true });
            ddlistItems.Add(new SelectListItem { Text = "1 Day", Value = "1Day" });
            ddlistItems.Add(new SelectListItem { Text = "5 Days", Value = "5Days" });
            ddlistItems.Add(new SelectListItem { Text = "15 Days", Value = "15Days" });
            ddlistItems.Add(new SelectListItem { Text = "30 Days", Value = "30Days" });
        }
        <div style="padding-bottom: 10px;">
            Show certificates expiring in:  @Html.DropDownList("ddlTimeFrame", new SelectList(ddlistItems, "Value", "Text"))
            @*<button type="submit" class="btn btn-sm btn-primary btn-prev" id="btnPrev">
                <i class="fa fa-refresh"></i> Reload Grid
            </button>*@
        </div>
    </form>
    <div style="width: 100%; overflow: auto;">
        <table id="jqgrid"></table>
        <div id="pjqgrid"></div>
    </div>
    <br>
</div>
<!-- end widget content -->

<!-- Style for Grid data load -->
<style type="text/css">
    .ui-jqgrid .loading {
        background-image: url("../../Content/img/ajax-loader.gif");
        border: 2px solid #706457;
        background-repeat: no-repeat;
        background-color: ghostwhite;
        border-radius: 10px;
        top: 20%;
        min-height: 102px; 
        min-width: 102px;
    }
</style>

<script src="~/Scripts/libs/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
    // DO NOT REMOVE : GLOBAL FUNCTIONS!
    /* Function to Get Profile Count */
    $(document).ready(function () {
        // Fronend UI Script
        pageSetUp();

        /* Function to Get Environment Details */
        function GetEnvironment(ipAddress) {
        }

        var timeRange;
        // Trigger reload Dropdown selection change event
        $("#ddlTimeFrame").change(function () {
            timeRange = $("#ddlTimeFrame option:selected").val();
            // Callback operation to load filtered data 
            $.ajax({
                type: 'GET',
                contentType: "application/json",
                url: '/Network/GetCertDetails',
                data: {timeframe: timeRange},
                success: function (returnedData) {
                    // This returns correct data but JQ Grid is not updated.
                    jQuery("#jqGrid").setGridParam({ datatype: 'json', data: returnedData }).trigger('reloadGrid');
                    var gridData = jQuery("#jqgrid").jqGrid('getRowData');
                    alert(gridData);
                }
            });
        });

        Date.prototype.addDays = function (days) {
            this.setDate(this.getDate() + parseInt(days));
            return this;
        };

        $.jgrid.defaults.loadtext = '';

        jQuery("#jqgrid").jqGrid({
            url: '/Network/GetCertDetails',
            postData: {
                timeframe: function () { return $("#ddlTimeFrame option:selected").val(); }
            },
            mtype: 'GET',
            datatype: 'json',
            height: 'auto',
            colNames: ['Common Name', 'Certificate', 'Device', 'Expiry Date',
                'Profile', 'Virtual', 'Partition', 'Pool',
                'VIP', 'Virtual Port', 'Member Name', 'Member IP Address',
                'Member Port', 'Environment', 'ATC Name', 'ATC Email ID'],
            colModel: [
                { name: 'Common_Name', index: 'Common_Name', sortable: true, width: 200 },
                { name: 'Certificate', index: 'Certificate', sortable: true, width: 250 },
                { name: 'Device', index: 'Device', sortable: true },
                { name: 'Expiry_Date', index: 'Expiry_Date', formatter: 'date', formatoptions: { srcformat: 'd/m/Y', newformat: 'd/m/Y' }, sortable: true, align: "center"},
                { name: 'Profile', index: 'Profile', align: "left" },
                { name: 'Virtual', index: 'Virtual', align: "left" },
                { name: 'Partition', index: 'Partition', align: "left" },
                { name: 'Pool', index: 'Pool', align: "left" },
                { name: 'VIP', index: 'VIP', align: "left" },
                { name: 'Virtual_Port', index: 'Virtual_Port', align: "center", width: 90 },
                { name: 'Member_Name', index: 'Member_Name', align: "left" },
                { name: 'MemberIPAddress', index: 'MemberIPAddress', align: "left" },
                { name: 'Member_Port', index: 'Member_Port', align: "center", width: 90 },
                {
                    name: 'MemberIPAddress', index: 'Environment', sortable: true, align: "left", formatter: function (cellvalue, options, rowObject) {
                        var IPAddress = cellvalue;
                        return GetEnvironment(IPAddress);
                    }
                },                { name: 'ATCName', index: 'ATCName', align: "left" },
                { name: 'ATCEmail', index: 'ATCEmail', align: "left", width: 200 }
            ],
            ajaxGridOptions: { cache: false },
            autoencode: true,
            autowidth: true,
            beforeRefresh: function () {
                grid.jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid');
            },
            caption: "Certificate Details",
            emptyrecords: "No records to view",
            gridview: true,
            hoverrows: true,
            ajaxGridOptions: { cache: false },
            loadonce: true,
            loadui: 'block',
            multiboxonly: true,
            multiselect: true,
            pager: '#pjqgrid',
            rowList: [15, 20, 30, 50],
            rowNum: 15,
            rownumbers: true,
            sortname: 'srno',
            sortorder: "asc",
            toolbarfilter: true,
            viewrecords: true
        });

        // Add Filter on top of the column
        jQuery("#jqgrid").jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false, defaultSearch: "cn" });
        // Adding pagination
        jQuery("#jqgrid").jqGrid('navGrid', "#pjqgrid", {
            edit: false,
            add: false,
            del: false,
            reloadGridOptions: { fromServer: true },
            refreshstate: "current"
        });
    });

    $(window).on('resize.jqGrid', function () {
        $("#jqgrid").jqGrid('setGridWidth', $("#content").width());
    });
</script>

MVC控制器代码:

public ActionResult GetCertDetails(string timeframe, string ddlTimeFrame)
{
    using (NetworkAutomationContext NAC = new NetworkAutomationContext())
    {
        List<NetworkCertsATC_SP> results = new List<NetworkCertsATC_SP>();
        try
        {
            if (timeframe != null)
                ViewData["TimeFrame"] = timeframe;
            else
                ViewData["TimeFrame"] = "All";

            // Fetch Grid data filtered according to time frame
            DateTime ExpiryDate = DateTime.Now.Date;
            switch (timeframe)
            {
                case "All":
                    results = NAC.NetworkCMDB_Certss.ToList();
                    break;
                case "1Day":
                    ExpiryDate = ExpiryDate.AddDays(1);
                    results = NAC.NetworkCMDB_Certss.Where(record => record.Expiry_Date < ExpiryDate).ToList();
                    break;
                case "5Days":
                    ExpiryDate = ExpiryDate.AddDays(5);
                    results = NAC.NetworkCMDB_Certss.Where(record => record.Expiry_Date < ExpiryDate).ToList();
                    break;
                case "15Days":
                    ExpiryDate = ExpiryDate.AddDays(15);
                    results = NAC.NetworkCMDB_Certss.Where(record => record.Expiry_Date < ExpiryDate).ToList();
                    break;
                case "30Days":
                    ExpiryDate = ExpiryDate.AddDays(30);
                    results = NAC.NetworkCMDB_Certss.Where(record => record.Expiry_Date < ExpiryDate).ToList();
                    break;
                default:
                    results = NAC.NetworkCMDB_Certss.ToList();
                    break;
            }
        }
        catch (Exception ex)
        {
            var ErrorObject = new NetworkCertsATC_SP
            {
                Common_Name = "Error",
                Certificate = ex.Message,
                Device = "NA",
                Expiry_Date = DateTime.Now.Date,
                Profile = "NA",
                Virtual = "NA",
                Partition = "NA",
                Pool = "NA",
                VIP = "NA",
                Virtual_Port = 0,
                Member_Name = "NA",
                MemberIPAddress = "NA",
                Member_Port = 0,
                ATCEmail = "NA",
                ATCName = "NA",
                EnvironmentType = "NA"
            };
            results.Add(ErrorObject);
        }
        return Json(results, JsonRequestBehavior.AllowGet);
    }
}

编辑 1:添加了从控制器成功接收但未在 jqGrid 中更新的新数据的屏幕截图。

编辑 2:按照@Oleg 的建议更新了代码。但仍然面临同样的问题。这次没有调用 MVC 控制器。此外,JQuery 中的第二个断点也未命中:

编辑 3:更新代码后下一个错误的屏幕截图。

如果我正确理解你的问题,你应该更改 $("#ddlTimeFrame").change(...) 的代码。您不需要自己制作 $.ajax。在 change 事件处理程序中,您只需调用

jQuery("#jqGrid").trigger("reloadGrid", { fromServer: true });

如果你使用 free jqGrid fork 或使用

var $grid = jQuery("#jqGrid");
var p = $grid.jqGrid("getGridParam");

p.datatype = "json";
$grid.trigger("reloadGrid");

如果使用旧版本的 jqGrid 或商业 Guriddo jqGrid。

顺便说一句。您目前使用的 beforeRefresh 回调代码似乎有误。如果你使用 free jqGrid fork 然后你可以删除它。如果你使用其他 jqGrid,那么你应该删除 .trigger('reloadGrid') 因为 jqGrid 在调用 beforeRefresh 回调后重新加载网格本身。此外,grid 变量似乎未定义。固定代码可能如下所示

beforeRefresh: function () {
    var p = $(this).jqGrid("getGridParam"); // get reference to internal parameters
    p.datatype = "json";
}

已更新:小心使用 id 的大小写:您在 HTML 中使用了小写:<table id="jqgrid"></table> 并且在创建网格时使用了正确的大小写(参见 jQuery("#jqgrid").jqGrid({...});)。另一方面,change 事件处理程序的代码(请参阅 $("#ddlTimeFrame").change(...);)使用 错误的 id 大小写(请参阅 jQuery("#jqGrid") 而不是 jQuery("#jqgrid")).这可能是您问题的根源。