在MVC3上,下拉列表定义为

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

如何通过javascript获取选定的值和/或文本?

我尝试传递一个名称:
  @Html.dropDownList(m=>m.model, new SelectList(m.myList, "value", "text"), new {name="name")

并从javascript中读取名称:
document.getElementByName(“name”)

但这不起作用。

最佳答案

如果您使用的是jQuery(在MVC项目中很有可能):

// 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();

当然,如果需要,您可以将其合并为一行。

如果您不使用jQuery,请参阅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;

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

var value = $("#ddl1").val();

10-04 22:30
查看更多