【问题标题】:Html.DropDownList - Disabled/ReadonlyHtml.DropDownList - 禁用/只读
【发布时间】:2009-10-28 09:32:43
【问题描述】:

在使用 MVC 的 Html.DropDownList 时,我需要设置什么选项才能使下拉框成为只读?

我尝试过类似......

Html.DropDownList("Types", Model.Types, new { _Enabled = "false" })

...以及沿着这条线的许多不同的东西;唉,不高兴!

我认为这很容易......而且可能是这样!

【问题讨论】:

  • 请注意下面@Thomas 的回答。将 Html.DropDownList 标记为禁用会阻止表单发布它保存的值。如何禁用控件或只读但仍提交表单值?
  • 如何用一个布尔值禁用动态设置属性?

标签: asp.net-mvc


【解决方案1】:

试试这个

Html.DropDownList("Types", Model.Types, new { @disabled = "disabled" })

【讨论】:

  • 但是这样做下拉列表的绑定值不会到达控制器。
  • 尝试使用它,但无论变化如何@Html.DropDownList("Tug_ID", model => model.Tug_ID, new { @disabled = "disabled" }) 都不起作用
  • 但这会阻止 DDL 值与表单一起提交。
  • 如果要在控制器上获取值,请为 DropdownList 添加隐藏字段。
  • @VishnuVikraman, This 可能是您的完美答案,
【解决方案2】:

关于第 22 条渔获:

如果我们使用@disabled,则该字段不会发送到操作(Mamoud) 如果我们使用@readonly,下拉错误仍然允许您更改值

解决方法:使用@disabled,并在下拉后添加隐藏字段:

@Html.HiddenFor(model => model.xxxxxxxx)

然后它被真正禁用,并且也被发送到操作。

【讨论】:

  • 这是我找到的最有用的解决方案。我不知道为什么它的票数这么少。
  • 非常好的提示。我只关注了答案,没有看下面的评论,我花了 2 个小时才找出为什么在回帖中设置了零值
  • 你必须小心这个解决方案:MVC 将打印两个具有id="MyModelField" 属性的元素,如果你愿意使用 JS 与选择/隐藏元素进行交互,这可能会很棘手。跨度>
  • 但这不是有效的 html。您将拥有两个具有相同 ID 的元素
  • 要解决@CătălinRădoi 提出的问题,只需使用 new {id = "SomeId"} 的自定义 ID 创建隐藏项
【解决方案3】:
<script type="text/javascript">
$(function () {
        $(document) .ajaxStart(function () {
                $("#dropdownID").attr("disabled", "disabled");
            })
            .ajaxStop(function () {
                $("#dropdownID").removeAttr("disabled");

            });

});
</script>

【讨论】:

  • 这个对我不起作用,你能扩展这个例子吗?
【解决方案4】:

我不得不禁用下拉列表并隐藏主 ID

<div class="form-group">
        @Html.LabelFor(model => model.OBJ_ID, "Objs", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("OBJ_ID", null, htmlAttributes: new { @class = "form-control", @disabled = "disabled"})
            @Html.HiddenFor(m => m.OBJ_ID)
            @Html.ValidationMessageFor(model => model.OBJ_ID, "", new { @class = "text-danger" })
        </div>
    </div>

【讨论】:

    【解决方案5】:

    一个对某些人来说可能很明显但对其他人来说不是很明显的提示..

    如果您使用基于DropDownListFor 的HTML 帮助程序,那么您的ID 将在HiddenFor 输入中重复。因此,您将拥有在 HTML 中无效的重复 ID,如果您使用 javascript 填充 HiddenForDropDownList,那么您将遇到问题。

    解决方法是在htmlattributes数组中手动​​设置id属性...

    @Html.HiddenFor(model => model.Entity)
    
    @Html.EnumDropDownListFor(
      model => model.Entity, 
      new { 
             @class = "form-control sharp", 
             onchange = "", 
             id =` "EntityDD", 
             disabled = "disabled" 
           }
    )
    

    【讨论】:

      【解决方案6】:

      或者你可以试试这样的:

      Html.DropDownList("Types", Model.Types, new { @readonly = "true" })
      

      【讨论】:

      • 这不起作用。下拉菜单显示为灰色,但仍处于启用状态且可用。
      • 嗨,我想仅根据值禁用/启用特定页面的下拉列表,我将其传递给模型。我尝试将 true / false 传递给残疾人,但它不起作用。你能帮忙吗
      【解决方案7】:

      把它放在样式里

       select[readonly] option, select[readonly] optgroup {
              display: none;
          }
      

      【讨论】:

        【解决方案8】:

        我只是这样做,然后收工

        Model.Id > -1 ? Html.EnumDropDownListFor(m => m.Property, new { disabled = "disabled" }) : Html.EnumDropDownListFor(m => m.Property)
        

        【讨论】:

          【解决方案9】:
          @Html.DropDownList("Types", Model.Types, new { @disabled = "" })
          

          作品

          【讨论】:

            【解决方案10】:

            Html.DropDownList("Types", Model.Types, new { @disabled = "disabled" }) @Html.Hidden(Model.Types) 为了保存和恢复数据,请使用隐藏控件

            【讨论】:

              【解决方案11】:

              为了完整起见,这里是 DropDownListFor 的 HTML 帮助程序,它添加了启用的参数,当 false 选择被禁用时。它保留在标记中定义的 html 属性,或者它允许在标记中使用 html 属性,它将选择值发布到服务器并且使用非常干净和简单。

              这里是助手的代码:

              public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, object htmlAttributes, bool enabled)
              {
                if (enabled)
                {
                  return SelectExtensions.DropDownListFor<TModel, TProperty>(html, expression, selectList, htmlAttributes);
                }
              
                var htmlAttributesAsDict = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
                htmlAttributesAsDict.Add("disabled", "disabled");
                string selectClientId = html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression));
                htmlAttributesAsDict.Add("id", selectClientId + "_disabled");
              
                var hiddenFieldMarkup = html.HiddenFor<TModel, TProperty>(expression);
                var selectMarkup = SelectExtensions.DropDownListFor<TModel, TProperty>(html, expression, selectList, htmlAttributesAsDict);
                return MvcHtmlString.Create(selectMarkup.ToString() + Environment.NewLine + hiddenFieldMarkup.ToString());
              }
              

              和用法,如果选项中只有一项,目标是禁用选择,标记:

              @Html.DropDownListFor(m => m.SomeValue, Model.SomeList, new { @class = "some-class" }, Model.SomeList > 1)
              

              还有一个更优雅的 HTML Helper 示例,目前不支持 post(非常简单的工作,只需使用 HAP 并将隐藏输入添加为根元素兄弟并交换 id):

              public static MvcHtmlString Disable(this MvcHtmlString previous, bool disabled, bool disableChildren = false)
              {
                if (disabled)
                {
                  var canBeDisabled = new HashSet<string> { "button", "command", "fieldset", "input", "keygen", "optgroup", "option", "select", "textarea" };
                  var doc = new HtmlDocument();
                  doc.LoadHtml(previous.ToString());
                  var rootElements = doc.DocumentNode.Descendants().Where(
                    hn => hn.NodeType == HtmlNodeType.Element && 
                    canBeDisabled.Contains(hn.Name.ToLower()) && 
                    (disableChildren || hn.ParentNode.NodeType == HtmlNodeType.Document));
              
                  foreach (var element in rootElements)
                  {
                    element.SetAttributeValue("disabled", "");
                  }
                  string html = doc.DocumentNode.OuterHtml;
                  return MvcHtmlString.Create(html);
                }
                return previous;
              }
              

              例如有一个模型属性 bool AllInputsDisabled,当为 true 时,所有的 html 输入都应该被禁用:

              @Html.TextBoxFor(m => m.Address, new { placeholder = "Enter address" }).Disable(Model.AllInputsDisabled)
              
              @Html.DropDownListFor(m => m.DoYou, Model.YesNoList).Disable(Model.AllInputsDisabled)
              

              【讨论】:

                【解决方案12】:

                你可以使用这种方法

                禁用除所选选项之外的所有选项:

                <select>
                    <option disabled>1</option>
                    <option disabled>2</option>
                    <option selected>3</option>
                </select>
                

                这样下拉菜单仍然提交,但用户无法选择其他值。

                使用 jQuery

                <script>
                    $(document).ready(function () {
                        $('#yourSelectId option:not(:selected)').prop("disabled", true);
                    });
                </script>
                

                【讨论】:

                • OP 专门询问 Html.DropDownList 在 MVC 中的使用。
                【解决方案13】:

                尝试使用@disabled 和jquery,这样您就可以在Controller 上获取值。

                Html.DropDownList("Types", Model.Types, new {@class = "your_class disabled", @disabled= "disabled" })
                

                添加一个名为“disabled”的类,以便您可以通过搜索该类来启用(在多个禁用字段的情况下),然后您可以使用“setTimeout”以防验证属性不进入控制器

                <script>
                
                  function clickSubmit() {
                    $("select.disabled").attr("disabled", false);
                    setTimeout(function () {
                        $("select.disabled").attr("disabled", true);
                    }, 500);
                  }
                </script>
                

                像这样的提交按钮。

                 <button type="submit" value="Submit" onclick="clickSubmit();">Save</button>
                

                如果是输入,只需使用@readonly="readonly"

                @Html.TextBoxFor("Types",Model.Types, new { @class = "form-control", @readonly= "readonly" })
                

                【讨论】:

                  【解决方案14】:

                  在参考了所有 cmets 和答案之后,我创建了这个答案。 这将解决下拉填充错误,即使它被禁用。

                  步骤 01

                  Html.DropDownList("Types", Model.Types, new {@readonly="readonly"})

                  步骤 02 这是css指针事件删除代码。

                  <style type="text/css">
                      #Types {
                          pointer-events:none;
                      }
                  </style>
                  然后你可以得到预期的结果

                  经过测试和验证

                  【讨论】:

                    猜你喜欢
                    • 1970-01-01
                    • 1970-01-01
                    • 2012-05-19
                    • 2011-07-16
                    • 1970-01-01
                    • 2017-08-31
                    • 1970-01-01
                    • 2013-04-08
                    • 2022-12-16
                    相关资源
                    最近更新 更多