asp.net-mvc Html.DropDownList - 禁用/只读

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1636103/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-07 23:55:34  来源:igfitidea点击:

Html.DropDownList - Disabled/Readonly

asp.net-mvc

提问by ETFairfax

What option do I need to set to make a drop down box readonly when using MVCs Html.DropDownList?

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

I've tried things like....

我试过这样的事情......

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

...and many different things along this line; alas no joy!

...以及沿着这条线的许多不同的事情;唉,没有快乐!

I thought this would be an easy.....and it probably is!

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

回答by Tadas ?ukys

Try this

尝试这个

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

回答by BGStack

Regarding the catch 22:

关于捕获 22:

If we use @disabled, the field is not sent to the action (Mamoud) And if we use @readonly, the drop down bug still lets you change the value

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

Workaround: use @disabled, and add the field hidden after the drop down:

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

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

Then it is truly disabled, and sent to the to the action too.

然后它真的被禁用了,并且也被发送到了动作。

回答by Muhammad Mubashir

<script type="text/javascript">
$(function () {
        $(document) .ajaxStart(function () {
                $("#dropdownID").attr("disabled", "disabled");
            })
            .ajaxStop(function () {
                $("#dropdownID").removeAttr("disabled");

            });

});
</script>

回答by cagedwhale

I had to disable the dropdownlist and hide the primary ID

我不得不禁用下拉列表并隐藏主 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>

回答by kirk

Put this in style

把这个风格化

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

回答by Bruce

Or you can try something like this:

或者你可以尝试这样的事情:

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

回答by Michael

A tip that may be obvious to some but not others..

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

If you're using the HTML Helper based on DropDownListForthen your ID will be duplicated in the HiddenForinput. Therefore, you'll have duplicate IDs which is invalid in HTML and if you're using javascript to populate the HiddenForand DropDownListthen you'll have a problem.

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

The solution is to manually set the ID property in the htmlattributes array...

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

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

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

回答by lollmbaowtfidgafgtfoohwtbs

I just do this and call it a day

我只是这样做,并称它为一天

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

回答by Antonio Bakula

For completeness here is the HTML Helper for DropDownListFor that adds enabled parameter, when false select is disabled. It keeps html attributes defined in markup, or it enables usage of html attributes in markup, it posts select value to server and usage is very clean and simple.

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

Here is the code for helper:

下面是助手的代码:

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());
}

and usage, goal is to disable select if there is just one item in options, markup:

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

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

And there is one even more elegant HTML Helper example, no post support for now (pretty straight forward job, just use HAP and add hidden input as root element sibling and swap id's):

还有一个更优雅的 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;
}

For example there is a model property bool AllInputsDisabled, when true all html inputs should be disabled:

例如,有一个模型属性 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)

回答by Pablo García Alves

You could use this approach

你可以使用这种方法

Disabling all the options except the selected one:

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

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

This way the dropdown still submits, but the user can not select another value.

这样下拉菜单仍然提交,但用户不能选择另一个值。

With jQuery

使用 jQuery

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