已禁用DropDownList razor mvc

在我的剃刀视图中,我使用下拉列表。 我希望禁用此控件(不可选)。

我的代码是:

@Html.DropDownListFor(model => model.LinguaCodiceMadre, Model.LinguaMadreList, new{ @disabled = "disabled" })

但它不起作用,我的控制始终启用。 Html页面代码是:

   Albanian German English French Italian Portuguese Russian Spanish  

没有“禁用”属性。

我的真正目标是有条件地启用/禁用下拉列表,如下所示:

 
@Html.DropDownListFor(model => model.LinguaCodiceMadre, Model.LinguaMadreList, new{@disabled=Model.IsDisabled ? "disabled" : "false"})

但它不起作用。

我试过两个

 new{@disabled=Model.IsDisabled ? "disabled" : "false"} 

 new{disabled=Model.IsDisabled ? "disabled" : "false"} 

但没有,禁用属性不在html页面上呈现。

有人有想法吗?

只是一个小小的修正。 试试这个

 
@Html.DropDownListFor(model => model.LinguaCodiceMadre, Model.LinguaMadreList, new{ disabled = "disabled" })

这肯定会禁用你的Drop-down ..

以及其他替代方案是使用jquery:

声明@Id为你的控制稍后做这样的事情

 $("#youid").prop("disabled", true); 

最后试试这个:如果这不工作意味着你身边的问题

 
@Html.DropDownListFor(model => model.LinguaCodiceMadre, Model.LinguaMadreList,String.Empty, new{ disabled = "disabled" })

问候

首先,如果要根据用户输入启用/禁用DropDown List,则需要使用javascript启用/禁用下拉列表。

对于Javascript使用以下逻辑:

 $("#checkbox1").change(function () { if (document.getElementById("checkbox1").checked == true) { document.getElementById("DropDown1").disabled = true; } else { document.getElementById("DropDown1").disabled = false; } }); 

这是我为你试过的小提琴演示,它完全令人担忧

小提琴演示

  1. 我有两个属性的模型
  2. 我在控制器中为DropDown填充测试数据以进行演示目的(在您的情况下,它将来自数据库)
  3. 在视图上,我为两个输入分配ID。
  4. 最后,在视图下面有一个Javascript函数正在驱动CheckBox以查看是否已选中,如果已选中,则无法从DropDown中选择任何值,否则它将对选择值开放。

我解决了我的问题:我的代码中有一个javascript(对不起,我没有立即注意到)在文档准备好时删除disable属性。

我做的是:

  • 为HtmlHelper创建扩展:

 public static class HtmlExtensions { public static MvcHtmlString DropDownListFor(this HtmlHelper html, Expression> expression, IEnumerable selectList, string optionText, bool canEdit) { if (canEdit) return html.DropDownListFor(expression, selectList, optionText); return html.DropDownListFor(expression, selectList, optionText, new { @disabled = "disabled" }); } } 
  • 在razor视图中:

 
@Html.DropDownListFor(model => model.LinguaCodiceMadre, Model.LinguaMadreList, "", Model.IsEnabled)

这有效!

谢谢