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 ?
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 yourselect
and simply create a parameter namedcmbDept
in the controller action your$.ajax
call is is posting to.you have 4 ways to do that
1. the you can bind ti the change event of the select
$(select).change(function(){})
and send anajax
request again wrapping the selected value which you will be able to get in thecontroller
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 themodel
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 aproperty
in themodel
with the namecmbDept
and selected value would be automatically posted backUs
FormCollection
as parameter in your controller. And assignname
to theselect
Now the
FormCollection
has this posted value.