Passing an array of values ​​in ASP.NET jQuery AJAX POST

I have a ListBox on my page, and I would like to make an AJAX post containing all the selected items. Here is 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 would like to pass the selected values ​​either as an array or a comma delimited string. What is the best way to transfer this data and how can I do it?

+1
source share
3 answers

To pass this as the correct JSON, the end result you are looking for is:

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

However, you serialize it, the first step is to output the selected values ​​as an array. jQuery.val () makes this easier than you expected:

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

"", JSON :

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

.NET JSON, array/collection selectedValues ( ), , . / int string, .NET .

, JSON.stringify() JSON , . , json2.js ( -, , , , ).

+2

? .

var formdata = $('#formId').serialize();

ajax

data: formdata,

-

. - #, , , . JSON ( ). JSON2 http://json.org , title .

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

mydata, .

+1

. = 1 & = 2 & = 3 jQuery serialize() http://api.jquery.com/serialize/

0
source

Source: https://habr.com/ru/post/1769420/


All Articles