简体   繁体   English

如何从下拉列表中获取ID?

[英]How to get id from dropdownlist?

I have a list: 我有一个清单:

public IList<SelectListItem> ToCountryList { get; set; }

I have this line in the razor view: 我在剃刀视图中有这行:

@Html.DropDownListFor(m => m.Filter.ToCountryId, Model.ToCountryList, string.Empty, new { style = "min-width: 100px; width:180px" })

Now I want jQuery to select ToCountryId from the selected value of the dropdownlist. 现在,我希望jQuery从下拉列表的选定值中选择ToCountryId
I need the id of the record. 我需要记录的ID。 For example - I have a pair: ID-NAME 5-USA. 例如-我有一对:ID-NAME 5-USA。 So I need to retrieve 5 (int) 所以我需要检索5(int)

How should I get the id? 我应该如何获得身份证?

This gives nothing: 这什么也没有:

$("select[name='Filter.ToCountryId'] option:selected").val()

HTML from browser (not sure how to publish - so plain text): 来自浏览器的HTML(不确定如何发布-纯文本格式):

..select starts

select id="Filter_ToCountryId" name="Filter.ToCountryId" style="min-width: 100px; width:180px"

option tags with countries

..select ends

Just give your dropdown a deterministic id: 只需为您的下拉列表提供确定性ID:

@Html.DropDownListFor(
    m => m.Filter.ToCountryId, 
    Model.ToCountryList, 
    string.Empty, 
    new { id = "myddl", style = "min-width: 100px; width:180px" }
)

and then you could easily get the selected value using an id selector: 然后您可以使用id选择器轻松获得所选值:

$('#myddl').val()

您应该从选择本身而不是从选项中获取价值:

$("select[name='Filter.ToCountryId']").val()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM