问题描述
我想创建禁用,以便它们是不可选择的几个选项的下拉列表。这里是我的code:
I am trying to create a dropdown list with a few options disabled so that they are not selectable. Here is my code:
var places = new SelectList(new List<SelectListItem>
{
new SelectListItem { Selected = false, Text = "Virgin Islands", Value = "Virgin Islands"},
new SelectListItem { Selected = false, Text = "", Value = "", Disabled= true},
new SelectListItem { Selected = false, Text = "Canada", Value = "Canada", Disabled= true},
new SelectListItem { Selected = false, Text = "", Value = "", Disabled= true},
new SelectListItem { Selected = false, Text = "Other", Value = "Other"},
}, "Value", "Text");
不过,生成的HTML残疾人SelectListItem仅仅是:
However, generated HTML for the disabled SelectListItem is merely:
<option value=""></option>
我怎样才能生成下面的HTML
How can I generate the following HTML
<option disabled="disabled"></option>
从SelectListItem?
from SelectListItem?
谢谢!
推荐答案
的禁用
属性将只有当你用尊敬的的IEnumerable&LT; SelectListItem&GT;
,而不是的SelectList
(在的SelectList
构造器,你只设置的属性值
和文本
),并在任何情况下,很少有一点创建的IEnumerable&LT; SelectListItem&GT;
然后创建的SelectList
从它当帮手只接受的IEnumerable&LT; SelectListItem&GT;
The Disabled
property will only be respected if you use IEnumerable<SelectListItem>
, not SelectList
(in the SelectList
contructor, you are only setting the properties of Value
and Text
) and in any case there is little point creating IEnumerable<SelectListItem>
then creating SelectList
from it when the helper only accepts IEnumerable<SelectListItem>
var places = new List<SelectListItem>
{
new SelectListItem { Selected = false, Text = "Virgin Islands", Value = "Virgin Islands"},
new SelectListItem { Selected = false, Text = "", Value = "", Disabled= true},
....
};
然后在助手
@Html.DropDownList(m => m.YourProperty, model.places) // or (IEnumerable<SelectListItem>)ViewBag.places
边注:的SelectList
确实有一个重载的构造函数的IEnumerable disabledValues
作为参数(的)
Side note: SelectList
does have an overloaded constructor that takes IEnumerable disabledValues
as a parameter (refer documentation)
这篇关于.NET MVC 5.2.3:如何创造出SelectListItem的禁用选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!