Checkbox disabled attribute in ASP.NET MVC

后端 未结 4 911
生来不讨喜
生来不讨喜 2020-12-06 09:20

My ViewModel has a property of selected and selectable. Both are boolean. I would like my view to have a checkbox that is enabled when selectable is true and disabled when

4条回答
  •  星月不相逢
    2020-12-06 09:36

    The problem is when you have to add more than 1 HTML attribute. That's a mess:

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

    What I do to solve this is to use a IDictionary that is previously loaded:

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

    And then I create the checkbox component only once:

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

提交回复
热议问题