传递值的数组中的ASP.NET AJAX的jQuery POST [英] Passing an array of values in an ASP.NET jQuery AJAX POST

查看:490
本文介绍了传递值的数组中的ASP.NET AJAX的jQuery POST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的网页列表框,我想提出一个包含所有选定的项目一个AJAX职位。这是我的code:

I have a ListBox on my page, and I'd like to make an AJAX post containing all the selected items. Here's my code:

$('#btnSubmit').click(function() {
    $.ajax({
        type: "POST",
        url: 'Default.aspx/GetSelectedValues',
        data: '{selectedValues: }',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess
    });
});

<select id="lbItems" multiple="multiple">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
</select>

我想通过在选定的价值无论是作为数组或一个逗号分隔的字符串。什么是传递数据的最佳方式,我该怎么办呢?

I'd like to pass in the selected values either as an array, or a comma-delimited string. What's the best way to pass that data, and how can I do it?

推荐答案

要传递的正确的JSON,最终的结果你要找的是:

To pass that as proper JSON, the end result you're looking for is:

// Assuming 1, 2, and 4 are selected.
{ selectedValues: ['1', '2', '4'] }

不过你序列化,第一步将是拉动选择的值了作为一个数组。 jQuery的.VAL()使这更容易比你期望的:

However you serialize it, the first step will be to pull the selected values out as an array. jQuery's .val() makes this easier than you'd expect:

// Returns an array of #lbItems' selected values.
var selectedValues = $('#lbItems').val()

如果你正在寻找快速'东经脏的,你可以采取和建立这样一个JSON字符串数组:

If you're looking for quick 'n dirty, you can take that and build a JSON array string like this:

var json = '{ selectedValues: [' selectedValues.join(',') '] }';

顺便指出,到接受要做到你以后名为 selectedValues​​ (区分大小写)的数组/集合参数.NET JSON端点。您可以指定数组/集合作为无论是int型或字符串,以及.NET会自动处理的类型转换。

Passing that into a .NET JSON endpoint that accepts an array/collection parameter named selectedValues (case sensitive) should accomplish what you're after. You can specify the array/collection as either type int or string, and .NET will handle the type conversion automatically.

如果它得到任何比这更复杂,我建议的使用JSON.stringify()来构建用手做的JSON代替。较新的浏览器实现了原生的,但你需要包括json2.js在旧的浏览器(和它不会伤害任何东西,包括在较新的,它推迟到如果有其天然的功能)。

If it gets any more complex than that, I'd suggest using JSON.stringify() to build the JSON instead of doing it by hand. Newer browsers implement that natively, but you'll need to include json2.js in older browsers (and it doesn't hurt anything to include that in newer ones; it defers to their native functionality if available).

这篇关于传递值的数组中的ASP.NET AJAX的jQuery POST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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