Asp.net-mvc – How to submit local jqgrid data and form input elements

asp.net-mvcjqgridsubmit

Page contains single form with input elements and jqgrid data.
jqGrid data is retrieved in json using loadonce: true option.
Data is edited locally.

How to submit all this data if submit button is pressed?
Has jqGrid any method which can help to submit all data from all rows. jqGrid – How to edit and save multiple rows at once? mentions that jQuery ajax form plugin should be used but I havent found any sample.

jqGrid probably holds retrieved json table in element. In this case form plugin is not capable read this data.

How to get and submit all data retrieved using loadonce: true and edited?

Update1

Based on Oleg answer I tried:

function SaveDocument()  {
  var gridData = $("#grid").jqGrid('getGridParam','data');
  var postData = JSON.stringify(gridData);    
  $('#_detail').val( postData );
  var res = $("#Form").serializeArray();
  $.ajax({ type: "POST",        
  url: 'Edit'
  data : res
  });
   }
}

aspx page:

<form id="Form" class='form-fields'>
.... other form fields
<input name='_detail' id='_detail' type='hidden' />
</form>
<div id="grid1container" style="width: 100%">
   <table id="grid">
   </table>
</div>

In ASP.NET MVC2 Controller Edit method I tried to parse result using

public JsonResult Edit(string _detail) {

var order = new Order();
UpdateModel(order, new HtmlDecodeValueProviderFromLocalizedData(ControllerContext));

var serializer = new JavaScriptSerializer();
var details = serializer.Deserialize<List<OrderDetails>>>(_detail);
}

Exception occurs in Deserialize() call. Decimal and date properties are passed in localized format but it looks like Deserialize() does not parse
localized strings and there is no way to force it to use converter like HtmlDecodeValueProviderFromLocalizedData passed to UpdateModel.

How to fix ?
Is is reasonable/how to convert _detail parameter into NameValue collection and then use UpdateModel to update details, use some other deserialize or other idea ?

Update 2.

Decimal and Date CurrentUICulture values are present in form and in jqGrid data. Sample provided handles them in form OK but fails for jqGrid data.
This controller should handle different entity types, form fields and jqgrid columns can defined at runtime. So using hard-coded names is not possible.
Based on Oleg reply I tried to override decimal conversion by creating converter

public class LocalizedTypeConverter : JavaScriptConverter
{
    public override IEnumerable<Type> SupportedTypes
    {
        get
        {
            return new ReadOnlyCollection<Type>(new Type[] { typeof(decimal) });
        }
    }

    public override object Deserialize(IDictionary<string, object> dictionary, Type type,
            JavaScriptSerializer serializer)
    {
        if (dictionary == null)
            throw new ArgumentNullException("dictionary");
        if (type == typeof(decimal))
            return decimal.Parse(dictionary["resources"].ToString(), CultureInfo.CurrentCulture);
        return null;

    }

    public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
    {
        throw new InvalidOperationException("We only Deserialize");
    }
}

But conversion still causes exception

0,0000 is not valid value for decimal. It looks like decimal converter cannot overridden. How to fix ?

Best Answer

First of all you can get all local data from the jqGrid with respect of

var localGridData = $("#list").jqGrid('getGridParam','data');

If you will need to send only subset of rows of the grid, like the selected rows only, you can need to get _index:

var idsToDataIndex = $("#list").jqGrid('getGridParam','_index');

To send the data to the server you can use the following function for example

var sendData = function(data) {
    var dataToSend = JSON.stringify(data);
    alert("The following data are sending to the server:\n" + dataToSend);
    $.ajax({
        type: "POST",
        url: "yourServerUrl",
        dataType:"json",
        data: dataToSend,
        contentType: "application/json; charset=utf-8",
        success: function(response, textStatus, jqXHR) {
            // display an success message if needed
            alert("success");
        },
        error: function(jqXHR, textStatus, errorThrown) {
            // display an error message in any way
            alert("error");
        }
    });
};

In the demo you will find a little more sophisticated example having two buttons: "Send all grid contain", "Send selected rows". The corresponding code is below

$("#sendAll").click(function(){
    var localGridData = grid.jqGrid('getGridParam','data');
    sendData(localGridData);
});
$("#sendSelected").click(function(){
    var localGridData = grid.jqGrid('getGridParam','data'),
        idsToDataIndex = grid.jqGrid('getGridParam','_index'),
        selRows = grid.jqGrid('getGridParam','selarrrow'),
        dataToSend = [], i, l=selRows.length;
    for (i=0; i<l; i++) {
        dataToSend.push(localGridData[idsToDataIndex[selRows[i]]]);
    }
    sendData(dataToSend);
});

where

var grid = $("#list"),
    decodeErrorMessage = function(jqXHR, textStatus, errorThrown) {
        var html, errorInfo, i, errorText = textStatus + '\n<br />' + errorThrown;
        if (jqXHR.responseText.charAt(0) === '[') {
            try {
                errorInfo = $.parseJSON(jqXHR.responseText);
                errorText = "";
                for (i=0; i<errorInfo.length; i++) {
                   if (errorText.length !== 0) {
                       errorText += "<hr/>";
                   }
                   errorText += errorInfo[i].Source + ": " + errorInfo[i].Message;
                }
            }
            catch (e) { }
        } else {
            html = /<body.*?>([\s\S]*)<\/body>/i.exec(jqXHR.responseText);
            if (html !== null && html.length > 1) {
                errorText = html[1];
            }
        }
        return errorText;
    },
    sendData = function(data) {
        var dataToSend = JSON.stringify(data);
        alert("The following data are sending to the server:\n"+dataToSend);
        $.ajax({
            type: "POST",
            url: "yourServerUrl",
            dataType:"json",
            data: dataToSend,
            contentType: "application/json; charset=utf-8",
            success: function(response, textStatus, jqXHR) {
                // remove error div if exist
                $('#' + grid[0].id + '_err').remove();
                alert("success");
            },
            error: function(jqXHR, textStatus, errorThrown) {
                // remove error div if exist
                $('#' + grid[0].id + '_err').remove();
                // insert div with the error description before the grid
                grid.closest('div.ui-jqgrid').before(
                    '<div id="' + grid[0].id + '_err" style="max-width:' + grid[0].style.width +
                    ';"><div class="ui-state-error ui-corner-all" style="padding:0.7em;float:left;"><span class="ui-icon ui-icon-alert" ' +
                    'style="float:left; margin-right: .3em;"></span><span style="clear:left">' +
                    decodeErrorMessage(jqXHR, textStatus, errorThrown) + '</span></div><div style="clear:left"/></div>');
            }
        });
    };

I think, that more difficult and more complex problem you will become on the server. In case of concurrency errors, but I wrote you about the problems before. Exactly because of the problems I personally would never implement saving of multiple rows on the server.

UPDATED: To get data from the form you can use jQuery.serialize. You should use name attribute for all fields in the form which you want to serialize. All data which you need to send are

var allData = {
    localGridData: grid.jqGrid('getGridParam','data'),
    formData: $("#formid").serialize()
};

You can send the data exactly like I described before: sendData(allData).