[英]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.