get the select element in .NET using AJAX

2019-08-30 10:23发布

问题:

I have ajax function like this to run on HTML select list

$.ajax({
                type: "POST",
                url: urlemp,
                success: function (returndata) {
                    if (returndata.ok) {
                        //  var data = eval("" + returndata.data + "");
                        select.empty();
                        select.append($('<option>' + "" + '</option>'));
                        $.each(returndata.data, function (rec) {

                            select.append($('<option>' + returndata.data[rec].Name + '</option>'));
                        });
                        select.show('slow');
                        select.change();
                    }
                    else {
                        window.alert(' error : ' + returndata.message);
                    }

                }
            }
    );

and this is the HTML element

        <select id="cmbDept"></select>

How can i get the value of the selected item in the controller using MVC 3 ?

回答1:

Us FormCollection as parameter in your controller. And assign name to the select

<select id="cmbDept" name="cmbDept"></select>

Now the FormCollection has this posted value.

public ActionResult Index(FormCollection form)
    {
        string val = "";
        foreach (var key in form.AllKeys)
        {
            if (key.Contains("cmbDept"))
            {
                 val = form.Get(key);
            }
        }
        --your code here with the posted values
        return View();
    }


回答2:

you have 4 ways to do that
1. the you can bind ti the change event of the select $(select).change(function(){}) and send an ajax request again wrapping the selected value which you will be able to get in the controller

2. you can keep a hidden input in your view binded to a property in the view's model now bind to the change of the select and fill the input with the value this way whenever your form is posted back it will have the values properly binded to the model

3. @Don saved me from writing the third way so read his ans.

4. if you have a model that this view is binded to then simple keep a property in the model with the name cmbDept and selected value would be automatically posted back



回答3:

To get the value of the select element on the client, just use $("#cmbDept").val().

To get the value of the element once it's submitted to the server, add a name="cmbDept" to your select and simply create a parameter named cmbDept in the controller action your $.ajax call is is posting to.