需要帮助填充jqGrid

时间:2014-05-05 21:16:15

标签: jquery asp.net-mvc json jqgrid asp.net-ajax

我无法简单地用数据填充jqGrid。我看了一下这些文档,并希望有人可以帮我解决这个问题......

我已经验证了数据是从我的服务器端控制器方法返回的,如下所示。样本只适用于 fto 对象的记录。

Customer_Name = "X"
FuelTkt_ID = 2
Image_ID = "12345"
Ticket_No = 6460193
Trans_Timestamp = {3/19/2014 10:20:00 AM}
Vehicle_No = "123456"

public async Task<JsonResult> GetFilteredFuelTicketsAsync(HH_FuelTkt_Input id)
        {
            try
            {
                IEnumerable<HH_FuelTkt_Output> fto = await db.GetFilteredFuelTicketsAsync(id);

                return Json(fto, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                strRemedyTktResponse = IssueRemedyTicket("Class: FuelTktController" + CrLf + "Method: GetFilteredFuelTickets" + CrLf + "Error: " + ex.Message + CrLf + "InnerException: " + ex.InnerException + CrLf + "Source: " + ex.Source + CrLf + "StackTrace: " + ex.StackTrace);
                LogMessage.WriteEventLog("Class: FuelTktController" + CrLf + "Method: GetFilteredFuelTickets" + CrLf + "Error: " + ex.Message + CrLf + "InnerException: " + ex.InnerException + CrLf + "Source: " + ex.Source + CrLf + "StackTrace: " + ex.StackTrace, "FuelTktController", 1, strRemedyTktResponse);
                return null;
            }
        }

在我的客户端,我可以在结果中看到数据。 有人可以告诉我我在这里缺少什么来填充网格吗? 下面是我的网格代码,下面是回来的数据:

if (begDte <= endDte) {
                            $('#fuelTickets').jqGrid({
                                caption: "Fuel Tickets",
                                colModel: [
                                        { name: 'FuelTkt_ID', index: 'FuelTkt_ID', label: 'ID', width: 20, align: "right", editable: false },
                                        { name: 'Ticket_No', index: 'Ticket_No', label: 'Ticket', width: 60, align: "right", editable: false },
                                        { name: 'Customer_Name', index: 'Customer_Name', label: 'Customer', width: 150, editable: false },
                                        { name: 'Vehicle_No', index: 'Vehicle_No', label: 'Vehicle', width: 60, editable: false },
                                        { name: 'Trans_Timestamp', index: 'Trans_Timestamp', label: 'Date', width: 100, editable: false },
                                        { name: 'Image_ID', index: 'Image_ID', label: 'Image ID', width: 150, editable: false }
                                ],
                                pager: false,
                                viewRecords: true,
                                gridview: true,
                                autoWidth: true,
                                emptyRecords: "No records found",
                                onCellSelect: function (rowid, iCol, cellcontent) {
                                    var grid = $('#fuelTickets');
                                    var imageID = grid.jqGrid('getCell', rowid, 'Image_ID');
                                    if (imageID != "")
                                        DisplayReceipt(imageID);
                                }
                            })
                            var HH_FuelTkt_Input = {
                                Vehicle_No: $('#txtVehicleNbr').val(),
                                Customer_Name: $('#txtCustomerName').val(),
                                Trans_Timestamp_Begin: $('#dteBeginDate').val(),
                                Trans_Timestamp_End: $('#dteEndDate').val()
                            };
                            $.ajax({
                                url: '@Url.Action("GetFilteredFuelTicketsAsync")',
                                type: 'POST',
                                data: JSON.stringify(HH_FuelTkt_Input),
                                contentType: 'application/json; charset=utf-8',
                                dataType: 'json',
                                success: function (result) {
                                    var grid = $("#fuelTickets");
                                    grid.clearGridData();
                                    grid.addRowData(result);
                                },
                                error: function (jqXHR, jqXHR, textStatus, errorThrown) {
                                    alert("No record found: " + "textStatus: " + textStatus + "\r\n" + "errorThrown: " + errorThrown);
                                }
                            });
                        }

以下是回来的数据:

[Object { FuelTkt_ID=2, Ticket_No=6460193, Vehicle_No="123456", more...}, Object { FuelTkt_ID=3, Ticket_No=6460194, Vehicle_No="123456", more...}]

0
    Object { FuelTkt_ID=2, Ticket_No=6460193, Vehicle_No="123456", more...}

1
    Object { FuelTkt_ID=3, Ticket_No=6460194, Vehicle_No="123456", more...}

以下是个人记录:

0
    Object { FuelTkt_ID=2, Ticket_No=6460193, Vehicle_No="123456", more...}

Customer_Name
    "X"

FuelTkt_ID
    2

Image_ID
    "12345"

Ticket_No
    6460193

Trans_Timestamp
    "/Date(1395238800000)/"

Vehicle_No
    "123456"

1
    Object { FuelTkt_ID=3, Ticket_No=6460194, Vehicle_No="123456", more...}

Customer_Name
    "X"

FuelTkt_ID
    3

Image_ID
    "22856"

Ticket_No
    6460194

Trans_Timestamp
    "/Date(1395246000000)/"

Vehicle_No
    "123456"

正确的代码: 而不是处理关于&#34; 标题&#34;的过于复杂的文档。对于网格,以下解决了所有问题,而没有对我的服务器代码进行任何更改(无需在此处进行任何分页)。只需一个语句来填充jqGrid文档中从未提及的网格。

实际上,这里的文档中提到 ,但从未在一个让它更容易理解的例子中使用。

http://www.trirand.com/jqgridwiki/doku.php?id=wiki:retrieving_data

我发帖给所有人看,并从文档缺乏和标题的复杂性中受益。

以下js中填充网格的最重要的陈述如下:

$("#fuelTicketsGrid")[0].addJSONData(data);

所有这一切!

HTML

<div>
                <table id="fuelTicketsGrid" class="table"></table>
                <div id="GridPager"></div>
            </div>

JS

function LoadGridData() {
                var HH_FuelTkt_Input = {
                    Vehicle_No: $('#txtVehicleNbr').val(),
                    Customer_Name: $('#txtCustomerName').val(),
                    Trans_Timestamp_Begin: $('#dteBeginDate').val(),
                    Trans_Timestamp_End: $('#dteEndDate').val()
                };
                $.ajax({
                    url: '@Url.Action("GetFilteredFuelTicketsAsync", "Home")',
                    type: 'post',
                    data: JSON.stringify(HH_FuelTkt_Input),
                    dataType: 'json',
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        $("#fuelTicketsGrid")[0].addJSONData(data);
                    },
                    error: function (jqXHR, jqXHR, textStatus, errorThrown) {
                        alert("No record found: " + "textStatus: " + textStatus + "\r\n" + "errorThrown: " + errorThrown);
                    }
                });
            }

            $('#fuelTicketsGrid').jqGrid({
                jsonReader: { root: 'tkts', repeatitems: true },
                width: 'auto',
                height: 'auto',
                autowidth: true,
                rownumbers: false,
                rownumWidth: 30,
                rowNum: 10, 
                rowList: [5, 10],
                edit: false,
                viewRecords: true,
                gridview: true,
                caption: "Fuel Tickets",
                pager: '#GridPager',
                onCellSelect: function (rowid, iCol, cellcontent) {
                    var grid = $('#fuelTicketsGrid');
                    var imageID = grid.jqGrid('getCell', rowid, 'Image_ID');
                    if (imageID != "")
                        DisplayReceipt(imageID);
                },
                colModel: [
                    { name: 'FuelTkt_ID', label: 'ID', width: 20, align: "right" },
                    { name: 'Ticket_No', label: 'Ticket', width: 60, align: "right" },
                    { name: 'Customer_Name', label: 'Customer', width: 150 },
                    { name: 'Vehicle_No', label: 'Vehicle', width: 60 },
                    { name: 'Trans_Timestamp', label: 'Date', width: 100, formatter: 'date', formatoptions: { newformat: 'l, F d, Y g:i:s A' } },
                    { name: 'Image_ID', label: 'Image ID', width: 150 },
                ]
            });
            $('#fuelTicketsGrid').jqGrid('navGrid', '#GridPager', { add: false, edit: false, del: false, search: false, refresh: false });

1 个答案:

答案 0 :(得分:0)

我可以看到几个问题。首先,您的JSON格式不正确。它需要几个标题字段来告诉网格如何渲染。这来自他们的文档:

{ total: xxx, page: yyy, records: zzz, rows: [ 
{name1:”Row01″,name2:”Row 11″,name3:”Row 12″,name4:”Row 13″,name5:”Row 14″}, ... ]}

其次,我不知道你的工作方式是否有效,但我使用普通的ActionResult调用来获取控制器中的数据:

    public ActionResult GetGrid()
    {
        YourEntities db = new YourEntities();
        int page = int.Parse(Request.Params["page"]);
        int rp = int.Parse(Request.Params["rows"]);

        // Whatever method to get your total rows, divide by page size
        int total = (db.SomeModels.Count() / rp) + 1;

        // Populate your List
        IEnumerable<SomeViewModel> rows = db.SomeModels.OrderBy(p => p.Name).Select(p => new SomeViewModel
        {
            ID = p.ID,
            Name = p.Name,
            Description = p.Description,
        }).Skip((page - 1) * rp).Take(rp);

        JsonResult retVal = Json(new { page, total, rows }, JsonRequestBehavior.AllowGet);
        return retVal;
    }

最后,我在jQuery的Ajax调用中使用了一些差异:

    jQuery("#Grid").jqGrid({
        url: '@Url.Action("GetGrid", "Home")', 
        datatype: "json",
        mtype: "GET",
        cache: false,
        colNames: ['ID', 'Name', 'Description'],
        colModel: [
            { name: 'ID', width: 90, sortable: true, align: 'left', show: false },
            { name: 'Name', width: 320, sortable: true, align: 'left' },
            { name: 'Description', width: 320, sortable: true, align: 'left' },
        ],
        rowNum: 20,
        rowList: [20, 50, 100],
        pager: '#GridPager',
        sortname: 'Name',
        height: '550px',
        width: 850,
        edit: false,
        viewrecords: true,
        sortorder: "desc",
        jsonReader: {
            repeatitems: false,
            id: "0"
        },
    });

无论如何,这对我有用:)

[编辑]

请参阅上文,了解有关在Linq中返回列表的更多详细信息。