簡體   English   中英

ASP.NET MVC 中的復選框禁用屬性

[英]Checkbox disabled attribute in ASP.NET MVC

我的 ViewModel 具有 selected 和 selectable 屬性。 兩者都是布爾值。 我希望我的視圖有一個復選框,當 selectable 為 true 時啟用,當 selectable 為 false 時禁用。 完成此操作的正確剃刀語法是什么?

我在表格中的項目列表上嘗試了下面的代碼。 無論可選值如何,每一行都會返回一個禁用的復選框。

 @Html.CheckBoxFor(modelItem => item.Selected, new { @disabled = !item.Selectable })

這是不容易有實現這個if輔助方法內部條件,因為所有下面的標記將呈現一個殘疾人chechbox。

<input type="checkbox" disabled>
<input type="checkbox" disabled="disabled">
<input type="checkbox" disabled="false">
<input type="checkbox" disabled="no">
<input type="checkbox" disabled="enabled">

這應該適用於剃須刀。 簡單的條件和渲染你想要的。

@if(item.Selected)
{ 
  @Html.CheckBoxFor(modelItem => item.Selected)
}
else
{
    @Html.CheckBoxFor(modelItem => item.Selected, new { @disabled = "disabled"})
}

您可以考慮編寫一個自定義 html 幫助程序,它為此呈現正確的標記。

這將不起作用,因為<input disabled="anything" />將導致禁用控件。 當它應該被禁用時,您只需要擁有一個 @disabled 屬性。

嘗試這樣的事情:

@Html.CheckBoxFor(modelItem => item.Selected, item.Selectable ?  (object)new {} :  (object)new { @disabled = "disabled" })

請注意,您可能需要強制轉換為(object)

問題是當您必須添加 1 個以上的 HTML 屬性時。 這是一團糟:

@if(item.Selected)
{ 
  @Html.CheckBoxFor(modelItem => item.Selected, new { @data_foo = "bar"})
}
else
{
    @Html.CheckBoxFor(modelItem => item.Selected, new { @data_foo = "bar", @disabled = "disabled"})
}

我為解決這個問題所做的是使用以前加載的IDictionary<string, object>

var htmlAttributes = new Dictionary<string, object>{
    {"data-foo", "bar"}
};
if(!item.Selected)
{
    htmlAttributes.Add("disabled", "disabled");
}

然后我只創建一次復選框組件:

@Html.CheckBoxFor(modelItem => item.Selected, htmlAttributes)

對不起,我之前的回答是錯誤的。

一旦禁用屬性,輸入元素將被禁用。 值是真還是假都沒有關系。 在 HTML 中,您不能將 disabled 設置為 false。

因此,您必須僅在條件有效時設置 disabled 屬性。

就像是:

object attributes = null;
if (!item.Selectable)
{
    attributes = new { disabled = "disabled"};
}
@Html.CheckBoxFor(modelItem => item.Selected, attributes)

暫無
暫無

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

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