MVC3:通过Javascript获取下拉菜单选定的值/文本



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

最新更新