【问题标题】:how to Dynamic setting Html.DropDownList attribute disabled in RazorView? [closed]如何在 RazorView 中禁用动态设置 Html.DropDownList 属性? [关闭]
【发布时间】:2017-05-31 03:13:02
【问题描述】:

这是我的下拉菜单:

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

上面的代码可以设置DropDownList被禁用,但是我想动态设置disabled属性与模型中的bool值。换句话说,如果 bool value = true,则启用 DropDownList,否则禁用 DropDownList。如何实现?

【问题讨论】:

  • 这有什么意义 - 禁用的属性不会回发它们的值,以及为什么在您需要显示属性的文本值时呈现所有选项。以及基于什么条件 - 您模型中的另一个属性?
  • 您在客户端寻找的是$('#Types').removeAttr("disabled")吗?我认为在某些情况下不鼓励在 DDL 中使用 disabled 属性,而是使用显示 HTML 帮助器。
  • 我刚刚编辑了,请看一下,我想在RazorView中用一个bool值禁用动态设置属性?
  • 您想使用模型中的哪个属性来禁用或启用下拉菜单?
  • @User3250,我想使用从后台到动态设置 DropDownList 禁用属性的布尔值

标签: c# asp.net-mvc html-select


【解决方案1】:

如果您想根据模型的属性禁用下拉菜单:

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

【讨论】:

  • 我想用另一种方式,使用禁用属性。谢谢!
  • @Superman 为什么你不想用阿迪加的答案?
  • 我想知道是否只能使用disabled属性来实现,我认为使用“if else”并不简洁
  • @Superman 我们不能对“禁用”使用三元运算符,所以我们必须使用 if else。这比创建自定义 html 帮助程序更简单易读。
【解决方案2】:

你可以试试下面的代码:

为 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)

【讨论】:

  • 谢谢! MVC自带的属性不能解析吗?必须扩展 HtmlHelper?
  • 对于您的要求对您有帮助
  • 你太棒了!你的方法很棒!
  • 很高兴它有帮助 :) 如果您发现它对您有用,请标记为将来参考的答案
猜你喜欢
  • 2013-06-18
  • 2011-09-21
  • 1970-01-01
  • 2020-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多