我需要在下拉列表中禁用几个项目。显然,"选择国家"和" -----"分隔符我已插入。该列表使用SelectListItem
创建,并在razor中使用DropDownListFor
呈现。
This article显示了一种方法,但我不确定如何实现该帮助。它也是4岁,我想知道目前是否还有更好/更简单的方法。 jQuery是一个选项,但如果可能的话,我希望避免这种情况。
$("#Country option[value*='-1']").prop('disabled', true);
还有更好的解决方案吗?
在控制器中:
public IEnumerable<SelectListItem> GetCountryList()
{
var countries = new SelectList(dbLocations.Countries, "Country", "CountryName").ToList();
countries.Insert(0, (new SelectListItem { Text = "Select Country", Value = "-1" }));
countries.Insert(1, (new SelectListItem { Text = "United Sates", Value = "USA" }));
countries.Insert(2, (new SelectListItem { Text = "Canada", Value = "CAN" }));
countries.Insert(3, (new SelectListItem { Text = "Mexico", Value = "MEX" }));
countries.Insert(4, (new SelectListItem { Text = "Brazil", Value = "BRA" }));
countries.Insert(5, (new SelectListItem { Text = "-----------", Value = "-1" }));
IEnumerable<SelectListItem> countrylist =
countries.Select(m => new SelectListItem()
{
Text = m.Text,
Value = m.Value
});
return countrylist;
}
在视图中:
@Html.DropDownListFor(
x => x.CountryCode,
new SelectList(Model.Countries, "Value", "Text"),
new { @class = "form-control" })
呈现HTML:
<select name="Country" id="Country">
<option value="-1">Select Country</option>
<option value="USA" selected="selected">United Sates</option>
<option value="CAN">Canada</option>
<option value="MEX">Mexico</option>
<option value="BRA">Brazil</option>
<option value="-1">------------------------</option>
<option value="ABW">Aruba</option>
<option value="AIA">Anguilla</option>
...
</select>