Reputation: 330
I have the following code which worked with me to pass whole select element:
Jquery:
$(".btn").click(function () {
var values = $('#id_cat option');
var optionsData = $.map(values, function (option) {
return option.text;
});
$.ajax({
type: "POST",
url: "/Products/Test03",
datatype: "text",
data: JSON.stringify(optionsData), //pass this variable to post request as 'options'
contentType: "application/json; charset=utf-8",
success: function (data) {
//alert('Success'); //.html(data);
},
error: function () {
alert('ERROR'); //$("#testarea").html("ERROR");
}
});
});
Controller:
public string Test03(IEnumerable<string> str1)
{
// call with two parameters and return them back
list = str1;
return list.FirstOrDefault().ToString();
}
Now I want to append the selected text in the select element and pass it along with the whole select elements. How can I do that?
Upvotes: 0
Views: 78
Reputation: 781300
You can use:
data: JSON.stringify({
options: optionsData,
selected: $("#id_cat_option option:selected").text()
}), //pass this variable to post request as 'options'
This will send a JSON object instead of an array as in your code. Use the .option
element to get the list of all options, and .selected
to get the text of the selected one.
And then change the controller method to
public ActionResult Test03(IEnumerable<string> options, string selected)
Upvotes: 1