我没有看到通过HtmlHelper
创建一个会吐出以下HTML的SelectListItem
的方法:
<option disabled="disabled">don't click this</option>
唯一属性SelectListItem
包括:
new SelectListItem{
Name = "don't click this",
Value = string.Empty,
Selected = false
}
我看到的唯一选择是
SelectListItem
进行子类化以添加Enabled
属性以获取视图的值HtmlHelper
扩展程序,该扩展程序接受我的新EnablableSelectList
并添加我的disabled
属性。答案 0 :(得分:22)
答案 1 :(得分:20)
在完全重新创建帮助程序之前,我可能会尝试这种方法。基本的想法是你从帮助程序得到的Html应该很好地形成,所以它应该是安全的解析。因此,您可以通过创建使用现有扩展的自己的扩展来增加该想法,但添加了禁用项目的功能。
这样的事情可能会做(完全未经测试)
public class CustomSelectItem : SelectListItem
{
public bool Enabled { get; set; }
}
public static class CustomHtmlHelpers
{
public static MvcHtmlString MyDropDownList(this HtmlHelper html, IEnumerable<CustomSelectItem> selectList)
{
var selectDoc = XDocument.Parse(html.DropDownList("", (IEnumerable<SelectListItem>)selectList).ToString());
var options = from XElement el in selectDoc.Element("select").Descendants()
select el;
foreach (var item in options)
{
var itemValue = item.Attribute("value");
if (!selectList.Where(x => x.Value == itemValue.Value).Single().Enabled)
item.SetAttributeValue("disabled", "disabled");
}
// rebuild the control, resetting the options with the ones you modified
selectDoc.Root.ReplaceNodes(options.ToArray());
return MvcHtmlString.Create(selectDoc.ToString());
}
}
答案 2 :(得分:5)
Clientside选项:例如,如果你给你的下拉列表一个“自定义”类和那些应该是不可选择的项值-1(例如),那么你可以这样做:
$('select.custom option[value=-1]').each(function () {
$(this).attr("disabled", "disabled");
});
答案 3 :(得分:0)
如果您要做的就是阻止用户从列表中选择某个值,那么使用输入验证似乎更简单,更省时的方法。如果你想验证他们已经做出了选择,那么你可能正在做的事情。
答案 4 :(得分:0)
-----选项1 控制器:
var ExpectedShipmentsRange = new List();
ExpectedShipmentsRange.Add(new SelectListItem() { Text = "Selected number of shipments", Value="0", Disabled = true, Selected = true });
ExpectedShipmentsRange.Add(new SelectListItem() { Text = "0 to 20 shipments", Value = "0-20" });
ExpectedShipmentsRange.Add(new SelectListItem() { Text = "20 to 40 shipments", Value = "20-40" });
ViewBag.ExpectedShipmentsRange = ExpectedShipmentsRange;
查看:
@Html.DropDownListFor(m => m.ExpectedShipments, (IEnumerable<SelectListItem>)@ViewBag.ExpectedShipmentsRange, new { @class = "form-control" })
-----选项2 控制器:
ViewBag.citiesSa = _dbContext.Countries.ToList();
查看:
@Html.DropDownListFor(m => m.City, new SelectList(@ViewBag.citiesSa, "Id", "Name"), "Select your city", new { @class = "form-control" })
-----选项3不支持禁用的选项:
List<SelectListItem> ExpectedShipmentsRange = new List<SelectListItem>();
ExpectedShipmentsRange.Add(new SelectListItem() { Text = "0 to 20 shipments", Value = "0-20" });
ExpectedShipmentsRange.Add(new SelectListItem() { Text = "20 to 40 shipments", Value = "20-40" });
ViewBag.ExpectedShipmentsRange = new SelectList(ExpectedShipmentsRange, "Value", "Text");
查看:
@Html.DropDownListFor(m => m.ExpectedShipments, (SelectList)@ViewBag.ExpectedShipmentsRange, new { @class = "form-control" })