Passing an array of values in an ASP.NET jQuery AJAX POST
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&开发者_JAVA技巧lt;/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?
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'] }
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()
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(',') '] }';
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.
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).
Is the select element inside a form tag? You can serialize the entire form and send it through easily.
var formdata = $('#formId').serialize();
Then in your ajax call
data: formdata,
--
Recently I dealt with a very similar issue. I am also using a C# Web Service, but the data I am dealing with is completely dynamic. I had to find a way to collect a variable length array and pass it as a single JSON string (along with some other fixed variables). I used the JSON2 library from http://json.org and collected the data by putting a certain class on all desired input fields, and using the title attribute as a key.
var formdata = {};
$(".formInputField").each(function() {
formdata[$(this).attr('title')] = $(this).val();
});
var mydata = JSON.stringify({ 'formdata': JSON.stringify(formdata), 'othervar' : otherVal1, 'othervar2' : otherVal2, 'othervar3' : otherVal3 });
Then I passed mydata
as above.
Pass it in the rest way. a=1&a=2&a=3 You may use jQuery serialize() http://api.jquery.com/serialize/
精彩评论