4

On MVC3, with a dropdownlist defined as

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

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

I tried passing a name:

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

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

but that does not work.

1 Answer 1

4

If you are using jQuery (which is highly likely with an 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 could combine this into a single line if desired.

If you aren't using jQuery, see https://stackoverflow.com/a/1085810/453277.

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

Manual ID:

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

var value = $("#ddl1").val();
Sign up to request clarification or add additional context in comments.

4 Comments

I have a couple of dropdownmenu on my view. How will I differentiate between them in the script?
You should use an ID to differentiate. Usually you can automatically obtain this from Html.IdFor() but you can also manually add an ID. I'll add an example.
Thanks alot. That worked. To get the selected value, i did var value = $("#ddl1 option:selected").val();
Just var value = $("#ddl1").val() will get the currently selected item. No need to add option:selected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.