MVC3:通过 Javascript 获取下拉菜单选择的值/文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13842328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MVC3: Get Drop down menu selected value/text via Javascript
提问by jpo
On MVC3, with a dropdownlist defined as
在 MVC3 上,下拉列表定义为
@Html.dropDownList(m=>m.model, new SelectList(m.myList, "value", "text"))
How can I get the selected value and/or text via javascript?
如何通过 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")
并从 javascript 中读取名称:document.getElementByName("name")
but that does not work.
但这不起作用。
采纳答案by Tim Medora
If you are using jQuery (which is highly likely with an MVC project):
如果您使用 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();
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.
如果您不使用 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;
Manual ID:
手册编号:
@Html.dropDownList(m=>m.model, new SelectList(m.myList, "value", "text"), new {id = "ddl1"})
var value = $("#ddl1").val();

