簡體   English   中英

帶有Html Helper的條件html屬性

[英]Conditional html attribute with Html Helper

我正在使用Html助手創建一個復選框。 在某些情況下,我想將disabled屬性添加到htmlAttribute對象。 我有以下代碼:

@if (Model.IsAuthorized)
{
    @Html.CheckBoxFor(x => @Model.Property, new { @class = "input-class" })
}
else
{
    @Html.CheckBoxFor(x => @Model.Property, new { @class = "input-class", @disabled = "disabled" })
}

我想讓這段代碼更簡潔。 有沒有辦法在一行中有條件地添加某些html屬性/沒有塊條件?

雖然你可以使用

@Html.CheckBoxFor(m => m.Property, Model.IsAuthorized ? (object)new { @class = "input-class", disabled = "disabled" } : (object)new { @class = "input-class"});

要在一行代碼中執行此操作,在您的情況下,可能會導致模型綁定失敗。

CheckBoxFor()方法生成2個輸入,一個value="True"的復選框和一個value="False"的隱藏輸入。 如果Property的初始值為trueIsAuthorizedtrue則結果是復選框被禁用且不會發布值。 但是隱藏的輸入將被提交並綁定到您的模型,導致Propertyfalse (當它應該為true

為了正確處理模型綁定,您需要if

@if (Model.IsAuthorized)
{
    @Html.CheckBoxFor(x => m.Property, new { @class = "input-class" })
}
else
{
    @Html.HiddenFor(m => m.Property) // necessary to post back the initial value
    <input type="checkbox" @(Model.Property ? "checked" : null) disabled />
}

請嘗試以下代碼:

@{
 var attr = new { @class = "input-class" };
 if (Model.IsAuthorized)
 {
    attr = new { @class = "input-class", @disabled = "disabled" };
 }
}
@Html.CheckBoxFor(x => @Model.Property, attr)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM