【问题标题】:How to make the @Html.EditorFor Disabled如何使@Html.EditorFor 禁用
【发布时间】:2013-10-31 10:17:50
【问题描述】:

我的 asp.net mvc Web 应用程序中有以下内容:-

<div><span class="f">Data Center Name</span> @Html.EditorFor(model => model.Switch.TMSRack.DataCenter.Name, new  { disabled = "disabled" })</div>

但是该字段不会被禁用,请问有人可以推荐吗? 谢谢

【问题讨论】:

  • 从 MVC 5.1 开始 @Html.EditorFor(model =&gt; model.Property, new { htmlAttributes = new { @disabled= "disabled" }})
  • 如果你使用的是asp核心,我在这里解释了一个解决方案:stackoverflow.com/a/44639822/6339469

标签: asp.net-mvc html-helper


【解决方案1】:

@Html.EditorFor() 没有支持 htmlAttributes 的重载。你可以试试@Html.TextBoxFor()

@Html.TextBoxFor(model => model.propertyName, new {disabled= "disabled" })

如果您在html属性中使用class等系统关键字,请在属性名称前添加@

例如:

@Html.TextBoxFor(model => model.propertyName, new {@class = "disabledClass" })

【讨论】:

  • 使用类和 TextBoxFor:@Html.TextBoxFor(model => model.Doctor.Label1, new { @class= "form-control", disabled = "disabled" })
  • 不是EditorFor不支持html属性,而是它用来显示控件的viewModels不支持。您可以在其中添加支持。
【解决方案2】:

使用 MVC 5,@Html.EditorFor() 支持 htmlAttributes

@Html.EditorFor(model => model.x, new { htmlAttributes = new { @class = "form-control", @disabled = "disabled" } })

上面的例子展示了如何添加一个类以及禁用的属性

【讨论】:

  • 我怎样才能使禁用的属性有条件?
  • 您可以使用 jQuery 通过 if 语句添加和删除 disabled 属性 $('.inputDisabled').prop("disabled", false); $('.inputDisabled').prop("disabled", true);
  • @LuisBecerril 你可以做类似if (@Model.IsReadOnly) { @Html.EditorFor(m =&gt; m.x, new { htmlAttributes = ... } else { @Html.EditorFor(m =&gt; m.x) } 的事情。您需要视图模型上的一个属性来指示控件是否应该是只读的。
  • 值得一提的是,禁用的字段值不会传递给控制器​​。相反,您将使用 @readonly = "readonly"
【解决方案3】:

另一种选择:将EditorFor用一个div或一个带有特定id的span包围,然后使用一点jquery/js:

  <span id="editors">      
        @Html.EditorFor(x => x.ViewModelProperty)
  </span>

    <!-- Disable above editors. EditorFor doesn't allow html attributes unfortunately. -->
    <script type="text/javascript">
        $(function () { $('#editors :input').attr("disabled", true); });
    </script>

【讨论】:

  • 为我的代码的“nop-editor”添加 Javascript 部分对我有用。 $('#DisplayOrderSection :input').attr("disabled", true);
【解决方案4】:

对于那些丢失文本值的人:禁用字段不会将其值传递给控制器​​。相反,请使用@readonly = "readonly"

@Html.EditorFor(model => model.EmployeeCode, new { htmlAttributes = new { @readonly = "readonly", @class = "form-control"} })

【讨论】:

    【解决方案5】:

    如果您在接受编辑更改时丢失了信息... 你可以试试

    <h3>@Model.x</h3>
    @Html.HiddenFor(model => model.x, new { htmlAttributes = new { @class = "form-control" } })
    

    【讨论】:

      【解决方案6】:

      您也可以使用EditorFor() 例如:

      @Html.EditorFor(model => model.Nama, new { htmlAttributes = new { @disabled ="true", @class = "form-control" } })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-04-29
        • 2012-06-10
        • 1970-01-01
        • 1970-01-01
        • 2012-04-09
        • 1970-01-01
        • 2020-11-01
        相关资源
        最近更新 更多