MVC3: Get dropdown menu, selected value / text using Javascript

In MVC3, with a drop-down list defined as

@Html.dropDownList(m=>m.model, new SelectList(m.myList, "value", "text")) 

How can I get the selected value and / or text through javascript?

I tried passing the name:

  @Html.dropDownList(m=>m.model, new SelectList(m.myList, "value", "text"), new {name="name") 

and reading the name from javascript: document.getElementByName ("name")

but it does not work.

+4
source share
1 answer

If you are using jQuery (which is very likely with the MVC project):

 // lambda to get the ID of your dropdown. This runs on the server, // and injects the ID into a client-side variable. var id = '@Html.IdFor( o => o.model )'; // get the dropdown by ID and wrap in a jQuery object for easy manipulation var dropdown = $("#" + id); // get the value var value = dropdown.val(); 

Of course, you can combine this into one line if you want.

If you are not using jQuery, see fooobar.com/questions/1150 / ....

 var id = '@Html.IdFor( o => o.model )'; var dropdown = document.getElementById( id ); var value = dropdown.options[dropdown.selectedIndex].value; 

Guide Id:

 @Html.dropDownList(m=>m.model, new SelectList(m.myList, "value", "text"), new {id = "ddl1"}) var value = $("#ddl1").val(); 
+4
source

All Articles