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

前端 未结 3 1118
执念已碎
执念已碎 2020-12-10 23:27

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() {
             


        
3条回答
  •  执念已碎
    2020-12-10 23:56

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

提交回复
热议问题