Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

c# - 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</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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...