简体   繁体   English

使用HTML Helper DropDownListFor添加选定的标签

[英]Add selected tag using HTML Helper DropDownListFor

I'm using ASP.NET HTML helpers to generate and HTML dropdown list. 我正在使用ASP.NET HTML帮助器来生成HTML下拉列表。 So basically I have the following code: 所以基本上我有以下代码:

  @Html.DropDownListFor(model => model.DropDownListName, new List<SelectListItem> { new SelectListItem{Text="Option 1", Value="1",Selected=true}, new SelectListItem{Text="Option 2", Value="2", Selected = false}, new SelectListItem{Text="Option 3", Value="3", Selected = false}}, new { @class = "myClass" }); 

The Helper does generate and HTML dropdown with the corresponding options, the problem is that I would like to add the "selected" attribute to the HTML tag corresponding to the selected value to the dropdown and this is not generated. Helper确实会生成带有相应选项的HTML下拉列表,问题是我想将“ selected”属性添加到与所选值相对应的HTML标记中,而不会生成。

Actually my final goal is to have a way to get the selected option in my JavaScript and here is the code I was using to do that before using an HTML Helper: 实际上,我的最终目标是要有一种在JavaScript中获取所选选项的方法,这是我在使用HTML Helper之前用来执行此操作的代码:

 var _selectedObjectId = parseInt($('#selectObject :selected').attr("id")); 

// To get the selected item in jQuery / Javascript:
var selected = parseInt( $("#DropDownListName").val() );

// To get the selected <option> HTML element:
var selectedOption = $("#DropDownListName option:selected");

// To get custom attributes other than the **value** (as in <option value="1"></option> then:
var id = selectedOption.attr("id");

// The story goes 

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

相关问题 将.Change()与dropdownlistFor一起使用(希望将选定的值作为文本添加到另一个div中) - using the .Change() with dropdownlistFor (want to add the values selected to another div as text) 在选定的 html 周围添加标签 - Add tag around selected html 如何从在 ASP.NET CORE MVC 中使用 @Html.DropDownListFor 标签助手的下拉按钮中获取值 - How to get the value from a dropdown button that uses @Html.DropDownListFor tag helper in ASP.NET CORE MVC 如何使用 jQuery 将 span 标记添加到选定文本并将更改永久保存在本地 html 文件中? - How to add span tag to a selected text using jQuery and saving the change permanently in local html file? 如何使用JavaScript将标签添加到选定的文本 - How to add tag to selected text, using javascript 使用HTML Helper在创建的TextBox元素中添加新的html属性 - Add new html attribute in the created TextBox element using Html Helper @ Html.DropDownListFor()即使选择了列表项,也始终显示空白 - @Html.DropDownListFor() Always Displays Blank even with a List Item selected Html.DropDownList对于每个选定值的不同功能 - Html.DropDownListFor different function for each value selected 如何向使用 HTML 帮助程序创建的下拉列表添加其他属性? - How to add additional attributes to a dropdown created using an HTML helper? 使用canvas标签在html中添加谷歌地图 - Add google map in html using canvas tag
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM