Aymen Kareem Aymen Kareem - 27 days ago 13
jQuery Question

How to retrieve the elements of a dropdownlist in jquery and send it with ajax to an MVC Controller in ASP.Net?

I have a select item as follows:

<select id="id_category">
<option> </option>
</select>


In run time there is a tree view used to fill up the select menu as follows:

<script>
$(document).ready(function () {
$('#data').jstree({
"plugins": ["checkbox"]
});

$("#data").on("changed.jstree", function (e, data) {
if (data.selected.length) {
$("#id_category").empty();
$(data.selected).each(function (idx) {
var node = data.instance.get_node(data.selected[idx]);
var s = document.getElementById('id_category');
s.options[s.options.length] = new Option(node.text, '1');
});
}
else
$("#id_category").empty();
});
});
</script>


and the html for the tree is not important now as it works well.

Now, I want when a user click on a button with HTML as follows:

<input id="btn3" type="button" value="Test 3" />


an ajax will be run to send all the items in the select to a controller in MVC as follows:

$("#btn3").click(function () {
$.ajax({
url: "/Products/Test03",
datatype: "text",
data: $.map($('#id_category')[0].options, function( elem ) { return (elem.value || elem.text); }),
type: "POST",
success: function (data) {
$('#testarea').html(data);
},
error: function () {
$("#testarea").html("ERROR");
}
});
});


and the controller:

[HttpPost]
public string Test03(Object str1)
{
// call with two parameters and return them back
this.myRetrievedData = str1;
return str1.ToString();
}


The above did not work with me, when I click on Test3 button nothing happened.
I am not sure how to pass the retrieved items to the function in the controller. Could anyone tell me how to do that?

Answer

The below logic must work for you. Many thanks to Mr.Stephen Muecke for assistance.

     $("#btn3").click(function () {

       var optionsData= $.map($('#id_category')[0].options, function(elem) {
                  return (elem.value || elem.text);
               }); // create a variable to hold all the options array.

        $.ajax({
            url: "/Products/Test03",
            datatype: "text",
            data: JSON.stringify(optionsData), //pass this variable to post request as 'options'
            contentType: "application/json; charset=utf-8",
            type: "POST",
            success: function (data) {
                $('#testarea').html(data);
            },
            error: function () {
                $("#testarea").html("ERROR");
            }
        });
    });

Then you can have your controller as below.

[HttpPost]
public string Test03(IEnumerable<string> options ) // change here to this
{
    //your logic goes here        
}