JavaScript 对象中具有重复名称的名称-值对列表

发布于 2024-12-06 08:49:01 字数 1747 浏览 0 评论 0原文

为了通过 AJAX 调用将表单数据提交到服务器以绑定 Telerik MVC 网格,我们可以在 OnDataBinding 事件到匿名 JavaScript 对象

<script type="text/javascript">
function Grid_onDataBinding(e) {
     var categoryValue = "Beverages";
     var priceValue = 3.14;

     // pass additional values by setting the "data" field of the event argument
     e.data = { 
        // the key ("category") specifies the variable name of the action method which will contain the specified value
        category: categoryValue,
        price: priceValue
     };
}
</script>

为了促进布尔值的模型绑定,ASP.NET MVC 生成复选框以及具有相同名称的隐藏文本字段

<input name="myCheckBox" class="check-box" id="myCheckBox" type="checkbox" CHECKED="checked" value="true"/>
<input name="myCheckBox" type="hidden" value="false"/>

,当提交这些字段时,提交的数据为

myCheckBox=true&MyCheckBox=false - 当选中复选框时

myCheckBox =false - 未选中复选框时

对于没有复选框的页面,可以通过

e.data = form.serializeObject()

where serializeObject 通过循环遍历所有表单字段来创建该对象。当存在如上所述的复选框时,如何在表单的情况下构造该对象?基本上,当名称允许重复时,名称-值对列表如何以对象形式表示?

e.data = { 
    textBox1: "some value1",
    myCheckBox: true //,
    //myCheckBox: false // ???
};

serializeObject 的实现为此类表单元素创建一个数组,并将这些元素提交为myCheckBox[]=true&myCheckBox[]=false 这会破坏服务器端的模型绑定。

For submitting the form data to the server from the AJAX call to bind Telerik MVC grid, we can set e.data in OnDataBinding event to a anonymous JavaScript object

<script type="text/javascript">
function Grid_onDataBinding(e) {
     var categoryValue = "Beverages";
     var priceValue = 3.14;

     // pass additional values by setting the "data" field of the event argument
     e.data = { 
        // the key ("category") specifies the variable name of the action method which will contain the specified value
        category: categoryValue,
        price: priceValue
     };
}
</script>

To facilitate the model binding for Boolean, ASP.NET MVC generates checkboxes along with a hidden text field with the same name

<input name="myCheckBox" class="check-box" id="myCheckBox" type="checkbox" CHECKED="checked" value="true"/>
<input name="myCheckBox" type="hidden" value="false"/>

and when these are submitted the data submitted is

myCheckBox=true&MyCheckBox=false - when the checkbox is checked

myCheckBox=false - when the checkbox is not checked

For pages where there is no checkbox, the post data can be easily obtained by

e.data = form.serializeObject()

where serializeObject creates that object by looping thru all the form fields. How to construct that object in case of forms when there are checkboxes as described above? Basically how can a name-value pair list be represented in the object form when the names are allowed to be duplicate?

e.data = { 
    textBox1: "some value1",
    myCheckBox: true //,
    //myCheckBox: false // ???
};

The implementation of serializeObject creates an array for such form elements and those are submitted as myCheckBox[]=true&myCheckBox[]=false which breaks the model binding on the server side.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

沒落の蓅哖 2024-12-13 08:49:01

您可以选择要序列化的特定表单子元素,而不仅仅是序列化整个表单。这允许您过滤掉您不想要的元素:

$('form input:not([type=hidden])').serializeObject();

编辑:根据 @amit_g 的评论,您需要在选中时使用复选框,或者在未选中时使用隐藏元素。这需要比 :not 选择器更复杂的过滤器:

$('form input')
    .filter(function() {
        if ($(this).attr('type') == 'hidden') {
            // filter out those with checked checkboxes
            var name = $(this).attr('name');
            return !$('form input[type=checkbox][name=' + name +']')
                .prop('checked');
        } else {
            // include all other input
            return true;
        }
    })
    .serializeObject();

请参阅此处的工作 jsFiddle:http://jsfiddle.net/nrabinowitz/nzmg7/4/

You can select specific form subelements to serialize, rather than just serializing the entire form. This allows you to filter out the ones you don't want:

$('form input:not([type=hidden])').serializeObject();

Edit: Per @amit_g's comment, you want the checkbox when it's checked or the hidden element when it's not. This requires a more complex filter than the :not selector:

$('form input')
    .filter(function() {
        if ($(this).attr('type') == 'hidden') {
            // filter out those with checked checkboxes
            var name = $(this).attr('name');
            return !$('form input[type=checkbox][name=' + name +']')
                .prop('checked');
        } else {
            // include all other input
            return true;
        }
    })
    .serializeObject();

See the working jsFiddle here: http://jsfiddle.net/nrabinowitz/nzmg7/4/

听风吹 2024-12-13 08:49:01

SerializeObject 在内部使用 serializeArrayserializeArray 仅序列化那些实际提交的元素。因此,使用以下代码,我禁用了与复选框对应的隐藏字段,并添加了一个更改事件来切换每个隐藏输入的禁用状态。由于输入被禁用,因此它们不会被序列化。

.serializeArray() 方法使用标准 W3C 规则
成功控制以确定应包含哪些元素;在
特别是元素不能被禁用并且必须包含名称
属性。没有序列化提交按钮值,因为表单没有被序列化
使用按钮提交。来自文件选择元素的数据不是
已连载。

$('form.form-class :checkbox').change(function () {
    enableDisableCorrespondingHiddenField($(this));
});

$('form.form-class :checkbox').each(function () {
    enableDisableCorrespondingHiddenField($(this));
});

enableDisableCorrespondingHiddenField(checkbox) {
    $(":hidden[name='" + checkbox.attr("name") + "']", checkbox.parent()).attr("disabled", checkbox.attr("checked"));
}

serializeObject uses serializeArray internally and serializeArray serializes only those elements that would be submitted actually. So using the following code, I have disabled the hidden fields corresponding to checkbox and added a change event to toggle the disbaled state on each hidden input. Since the inputs are disabled, they don't get serialized.

The .serializeArray() method uses the standard W3C rules for
successful controls to determine which elements it should include; in
particular the element cannot be disabled and must contain a name
attribute. No submit button value is serialized since the form was not
submitted using a button. Data from file select elements is not
serialized.

$('form.form-class :checkbox').change(function () {
    enableDisableCorrespondingHiddenField($(this));
});

$('form.form-class :checkbox').each(function () {
    enableDisableCorrespondingHiddenField($(this));
});

enableDisableCorrespondingHiddenField(checkbox) {
    $(":hidden[name='" + checkbox.attr("name") + "']", checkbox.parent()).attr("disabled", checkbox.attr("checked"));
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文