سؤال

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.

هل كانت مفيدة؟

المحلول

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();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top