John John
John John

Reputation: 1

How to make the @Html.EditorFor Disabled

I have the following inside my asp.net mvc web application :-

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

but the field will not be disabled ,, can anyone adivce please? THanks

Upvotes: 44

Views: 101770

Answers (6)

PKirby
PKirby

Reputation: 889

For those that lose your text value : Disabled fields does not pass its value to the controller. Instead, use @readonly = "readonly"

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

Upvotes: 7

remajabioinformatik
remajabioinformatik

Reputation: 31

You can also use EditorFor() eg:

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

Upvotes: 3

Armando Baltazar
Armando Baltazar

Reputation: 91

If you lose information when you accept the Edit-changes ... You could try

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

Upvotes: 4

SaadK
SaadK

Reputation: 1557

Using MVC 5, @Html.EditorFor() supports htmlAttributes

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

The above example shows how you can add a class and also the disabled attribute

Upvotes: 43

Kaf
Kaf

Reputation: 33839

@Html.EditorFor() does not have an overload to support htmlAttributes. You could try @Html.TextBoxFor()

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

If you are using system key words such as class in htmlAttributes please add @ before the attribute name.

Ex:

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

Upvotes: 70

Sava B.
Sava B.

Reputation: 1047

Another alternative: surround the EditorFor with a div or a span with a certain id, and then use a bit of 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>

Upvotes: 9

Related Questions