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

时间:2019-04-03 09:31:11

标签: c# jquery asp.net-mvc jqgrid

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

因此,请勿将此标记为重复或否决。请协助解决以下情况:

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

剃刀视图/ 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 :添加了从Controller成功接收但在jqGrid中未更新的新数据的屏幕截图。 enter image description here

编辑2 :已更新@Oleg建议的代码。但是仍然面临着同样的问题。这次没有调用MVC Controller。同样,JQuery中的第二个断点也没有命中: Updated code as suggested by @Oleg

编辑3 :更新代码后下一个错误的屏幕截图。 p = $grid.jqGrid("getGridParam"); is undefined.

1 个答案:

答案 0 :(得分:1)

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

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

如果您使用free jqGrid分叉或使用

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

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

在使用旧版本的jqGrid或商业Guriddo jqGrid的情况下。

顺便说一句。您当前使用的beforeRefresh回调代码似乎是错误的。如果使用free jqGrid叉子,则可以将其删除。如果使用其他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"))。这可能是您问题的根源。