Submitting jqGrid row data from view to controller

2020-06-06 02:52发布

I've been working on submitting all of the rows from a jqGrid to an action method using the general idea from this question and some code from the comments on the jqGrid Wiki. Essentially, on submit, I want ALL of the row data to get back to the controller so I can persist it. I've tried using a hidden field to store all of the row data, but the controller never seems to get everything, only the last edited cell in the grid. So I switched to an ajax approach, but no matter what I've tried I can't get the ajax POST to come across as JSON. Here's what I have right now:

$("#submitButton").click(function () {
    $("#awesomeGrid").jqGrid('resetSelection');
    var gridRows = $("#awesomeGrid").jqGrid('getRowData');
    var rowData = new Array();
    for (var i = 0; i < gridRows.length; i++) {
        var row = gridRows[i];
        rowData.push($.param(row));
    }
    var dataToSend = JSON.stringify(rowData);
    $.ajax({
        url: '@Url.Action("UpdateAwesomeGridData")',
        type: 'POST',
        data: { gridData: dataToSend },
        dataType: 'json',
        success: function (result) {
            alert('success');
        }
    });
    return true;
});

And my controller method signature:

[HttpPost]
public ActionResult UpdateAwesomeGridData(string gridData)

I've tried changing the gridData parameter from string to string[] to object[] to all sorts of stuff, and nothing seems to work. If I leave it as string, I get the data, but the format is all wacky, like this (column names substituted):

gridData=["Id=1&Field1=1945&Field2=0&Field3=0&Field4=1&Field5=Some+string+value&Field6=&Field7=&Field8=&Field9s=","Id=2&Field1=1945&Field2=0&Field3=0&Field4=2&Field5=Another+string+value&Field6=&Field7=&Field8=&Field9s=","Id=3&Field1=1945&Field2=0&Field3=0&Field4=3&Field5=Yet+another+string&Field6=&Field7=&Field8=&Field9s=","Id=4&Field1=1945&Field2=0&Field3=0&Field4=4&Field5=Final+string&Field6=&Field7=&Field8=&Field9s="]

I got this out of Fiddler, and for the record, the JSON tab shows nothing for the request when I fiddle it. Is there a way I can JSON-ify this array and send it in a single call? What type would my parameter be on my action method?

EDIT - Solution

For any other people that are as dumb as I am, here's how I got it to work:

First, on Oleg's suggestion, I added loadonce: true to the jqGrid definition. Then, changed my submit button function as follows:

$("#submitButton").click(function () {
    var griddata = $("#awesomeGrid").jqGrid('getGridParam', 'data');
    var dataToSend = JSON.stringify(griddata);
    $.ajax({
        url: '@Url.Action("UpdateAwesomeGridData")',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: dataToSend,
        dataType: 'json',
        success: function (result) {
            alert('success: ' + result.result);
        }
    });
    return true;
});

Then, changed my controller method signature:

public ActionResult UpdateAwesomeGridData(IEnumerable<GridBoundViewModel> gridData)

Hope this helps someone in the future.

3条回答
Rolldiameter
2楼-- · 2020-06-06 02:53

code send from Jsp Page:

  $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    url: "LoadDataservice.asmx/SaveData",
                    async: true,
                    data: '{"formData":"' + $('#check-user').serialize() + '"}',  // working
                    dataType: "json",
                    success: function (msg) {
                        $('#details').empty();
                        jsonArray = $.parseJSON(msg.d);
                        var $ul = $('<ul id="details">');
                        for (i = 0; i < jsonArray.length; i++) {
                            $("#details").append('<li id="' + i + '" name="head" >' + jsonArray[i].name + '</li>');
                        }
                        $('#details').listview('refresh');
                    },
                    error: function (msg) {
                        alert("Error");
                    }
                });

Action Class:

 public string SaveData(string formData)
        {

            string s = formData;
            var keyValuePairs = from array in
                                    (from kvpString in s.Split('&')
                                     select kvpString.Split('='))
                                select new KeyValuePair<string, string>(array[0].Trim(), array[1].Trim());
            var dictionary = keyValuePairs.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
            var username = dictionary["username"];
            var password = dictionary["password"];


            string details = "testing";

            return details;
        }
    }
查看更多
▲ chillily
3楼-- · 2020-06-06 02:58

I see many problem which you has.

The first problem is that you use $.param(row) and fill the array rowData with encoded (???!!!) data. I think the correct code should contain direct posting of the data returned from getRowData: data: { gridData: gridRows }. On the server side you can use UpdateAwesomeGridData(string gridData) and then convert gridData to the List<List<string>> for example by

JavaScriptSerializer serializer = new JavaScriptSerializer();
var myListOfData = serializer.Deserialize<List<List<string>>>(gridData);

I would like to go one step back and ask the question: why you need send the data to the server which it already has? If you need for some purpose all the data from the grid you can just use the same action of controller which generate the data and so you will have the same data already on the server.

Sending data to the server can be needed only in one scenario: you used loadonce: true, modified the data locally and at the end of modifications you need send all the changed data to the server. In the case the usage of getRowData would be not the best choice because it get you the data from the current page only. To get all the data you should better use getGridParam("data").

查看更多
祖国的老花朵
4楼-- · 2020-06-06 03:05

I see Oleg has already answered your question, and i have no mean to overwrite it, however i thought of sharing my idea here. I think passing data as an object to MVC controller makes more sense than just string and then you can pass that object to your DAO class.

Here is my jQuery code (obviously thanks to Oleg for this code).

        var ruledetail = new Array();
        var grid = $('#RuleCriteria')[0], rows = grid.rows,
                    cRows = rows.length, iRow, iCol;


        var fromvalue;

        for (iRow = 0; iRow < cRows; iRow++) {
            row = rows[iRow]; // row.id is the rowid
            if ($(row).hasClass("jqgrow")) {
                cellsOfRow = row.cells;

                //build rule detail data
                ruledetail.push({
                    ColumnName: jQuery('#RuleCriteria').jqGrid('getCell', row.id, 'ColumnName'), 
                    ColumnOperator: jQuery('#RuleCriteria').jqGrid('getCell', row.id, 'ColumnOperator'),
                    FromValue: fromvalue,
                    ToValue: $(cellsOfRow[4]).text(),
                    Connector: jQuery('#RuleCriteria').jqGrid('getCell', row.id, 'Connector')
                });

            }
        }


        var ruledata = JSON.stringify({ 'detaildata': ruledetail });

        $.ajax({
            url: "@Url.Action("CreateRules", "Admin")",
            data: ruledata,
            type: "POST",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function () {
                $(".Message").displayMessage("@Msg.Success");
                setTimeout(function () { location.href = "@Url.Action("Rule", AppType)"; }, 1000);
                },
            error: function () {
                $(".Message").displayError("@Msg.GeneralError");
                }
        });

And here goes my MVC code.

    [HttpPost]
    public ActionResult CreateRules(List<RuleData> detaildata)
    {

       RuleManager _savedata = new RuleManager();
       _savedata.Save(detaildata);
        var jsonData = "success";
        return Json(jsonData, JsonRequestBehavior.AllowGet);

    }
查看更多
登录 后发表回答