2017-05-31 31 views
0

这是我的下拉菜单:如何在RazorView中禁用动态设置Html.DropDownList属性?

@Html.DropDownList("OptionType", selectList, new { @class = "form-control", name = "OptionType",@disabled = "disabled" }) 

上面的代码可以设置DropDownList的是残疾人,但我想从模型中的布尔值动态设置禁止属性。换句话说,如果bool值= true,则启用DropDownList,否则禁用DropDownList。如何实现它?

+1

什么是这个被禁用的属性点不会回发它们的值,并且当你需要显示属性的文本值时,为什么会渲染所有选项。基于此模型的另一个属性是什么? –

+0

是您在客户端寻找的'$('#Types')。removeAttr(“disabled”)?我认为在某些情况下不鼓励在DDL中使用'disabled'属性,而是使用display HTML helper。 –

+0

我现在编辑它,请看看它一次,我想动态设置属性禁用RazorView中的一个布尔值? – Superman

回答

1

如果您要根据您的模型的属性,以停用下拉:

@if(Model.DisableDropdown) 
{ 
    @Html.DropDownList("OptionType", selectList, new { @class = "form-control", name = "OptionType",@disabled = "disabled" }) 
} 
else 
{ 
    @Html.DropDownList("OptionType", selectList, new { @class = "form-control", name = "OptionType" }) 
} 
+0

了解我想用另一种方式,使用禁用的属性。谢谢! – Superman

+0

@Superman为什么你不想使用Adiga的答案? – User3250

+0

我想知道是否只能使用禁用属性来实现它,我认为使用“if else”并不简洁 – Superman

1

你可以试试下面的代码:

创造的HtmlHelper扩展:

public static class HtmlExtensions 
{ 
    public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionText, bool IsDisabled) 
    { 
     if (IsDisabled) 
      return html.DropDownListFor(expression, selectList, optionText, new { @disabled = "disabled" }); 
     else 
      return html.DropDownListFor(expression, selectList, optionText); 

    } 
} 

在剃刀查看:

@Html.DropDownListFor(model => model.Type, Model.Types, "", Model.IsDisabled) 
+0

谢谢! MVC自己的属性无法解决它?必须扩展HtmlHelper? – Superman

+0

您的需求对您有帮助 –

+0

您太棒了!你的方式很棒! – Superman