get the select element in .NET using AJAX

2019-08-30 09:57发布

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 ?

3条回答
闹够了就滚
2楼-- · 2019-08-30 10:33

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.

查看更多
乱世女痞
3楼-- · 2019-08-30 10:35

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

查看更多
闹够了就滚
4楼-- · 2019-08-30 10:40

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();
    }
查看更多
登录 后发表回答