如何提交当地jqGrid的数据和表单输入元素 [英] How to submit local jqgrid data and form input elements

查看:1473
本文介绍了如何提交当地jqGrid的数据和表单输入元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

页包含输入元素和数据的jqGrid单一形式。
jqGrid的数据是使用JSON检索loadonce:true选项。
数据本地编辑。

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

如何提交所有这些数据如果pressed提交按钮?
已jqGrid的,它可以帮助从所有行提交的所有数据的任何方法。 <一href=\"http://stackoverflow.com/questions/3738778/jqgrid-how-to-edit-and-save-multiple-rows-at-once\">jqGrid - 如何编辑,并在一次保存多个行提到jQuery的Ajax表单插件应该使用,但我还没有发现任何样本?

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保存检索JSON表中的元素。在这种情况下插件的形式是不能够读取该数据。

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

如何获得和使用提交检索loadonce的所有数据:真实和编辑

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

UPDATE1

根据奥列格答案我想:

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页面:

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>

在ASP.NET MVC2控制器编辑方法,我试图解析使用效果

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);
}

在反序列化()调用时发生异常。小数和日期属性在本地化的格式通过,但它看起来像反序列化()不解析
本地化的字符串,有没有办法迫使它使用转换器像HtmlDe codeValueProviderFromLocalizedData传递的UpdateModel。

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.

如何解决?
难道是合理的/如何_detail参数转换成NameValue集合,然后使用的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 ?

更新2

十进制和日期的CurrentUICulture值在形式和的jqGrid数据present。提供了样本处理它们的形式确定的,但失败的jqGrid的数据。
该控制器应处理不同的实体类型,表单字段和列的jqGrid可以在运行时定义。因此,使用硬codeD的名字是不可能的。
基于奥列格回答我试图通过创建转换

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不是十进制有效值。它看起来像十进制转换器不能覆盖。如何解决?

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

推荐答案

首先,你可以从jqGrid的所有本地数据与尊重

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

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

如果您将需要发送网格的行只子集,像只选定行,你可以根据需要获得 _index

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");
        }
    });
};

的演示,你会发现有两个按钮,一个小更复杂的例子:发送所有网格含有,发送所选行。相应的code是低于

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);
});

其中,

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.

更新时间::您可以通过您可以使用表单数据 jQuery.serialize 。您应该使用名称属性,它要序列表单中的所有领域。您需要发送的所有数据都是

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()
};

您可以像我确切地描述发送数据之前:送出数据(ALLDATA)

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

这篇关于如何提交当地jqGrid的数据和表单输入元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆