2013-10-31 70 views
25

我有以下我的asp.net MVC Web應用程序中: -如何使@ Html.EditorFor殘疾人

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

,但該領域不會被禁用,,誰能書於好嗎? THanks

+12

從MVC 5.1起'@ H​​tml.EditorFor(model => model.Property,new {htmlAttributes = new {@ disabled =「disabled」}})' –

+0

如果您使用的是asp核心,我在這裏解釋了一個解決方案: https:// stackoverflow。 com/a/44639822/6339469 – HamedH

回答

46

@Html.EditorFor()沒有重載支持htmlAttributes。如果使用的是系統的關鍵字,如htmlAttributes class請屬性名稱前面加@你可以嘗試@Html.TextBoxFor()

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

例:

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

與兩個c lass和TextBoxFor: @ Html.TextBoxFor(model => model.Doctor.Label1,new {@class =「form-control」,disabled =「disabled」}) – MuniR

6

另一種替代方法:包圍EditorFor與一個div或具有一定ID的跨度,然後用一個比特的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> 
13

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

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

上面的例子說明如何添加一個類人所以殘疾人屬性

+1

不適用於我。我正在使用MVC 5 – MuniR

+0

如何使殘疾人屬性有條件? –

+0

您可以使用jQuery來添加和刪除if語句的禁用屬性 $('。inputDisabled')。prop(「disabled」,false); $('。inputDisabled')。prop(「disabled」,true); – SaadK

0

如果您在接受編輯,更改會丟失信息... 你可以嘗試

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

您還可以使用EditorFor() 如: - @Html.EditorFor(model => model.Nama, new { htmlAttributes = new { @class = "form-control", @disabled ="true" } })