Aymen Kareem Aymen Kareem - 11 months ago 46
Ajax Question

How to passing whole select element to a controller?

I have the following code which worked with me to pass whole select element:

  1. Jquery:

    $(".btn").click(function () {
    var values = $('#id_cat option');
    var optionsData = $.map(values, function (option) {
    return option.text;
    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");

    1. 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?

Answer Source

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)