Checkbox disabled attribute in ASP.NET MVC

后端 未结 4 892
生来不讨喜
生来不讨喜 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:35

    It is not easy to achieve this with an if condition inside the helper method because all the below markups will render a disabled 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">
    

    This should work in the razor. Simple If condition and rendering what you want.

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

    You may consider writing a custom html helper which renders the proper markup for this.

    0 讨论(0)
  • 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<string, object> that is previously loaded:

    var htmlAttributes = new Dictionary<string, object>{
        {"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)
    
    0 讨论(0)
  • 2020-12-06 09:41

    This won't work because <input disabled="anything" /> will result in a disabled control. You need to only have a @disabled property when it should be disabled.

    Try something like this:

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

    Note that you might need to cast to (object)

    0 讨论(0)
  • 2020-12-06 09:42

    Sorry, my previous answer was wrong.

    The input-element will be disabled as soon as it gets the attribute disabled. It doesn't matter if the value is true, false. In HTML you can't set disabled to false.

    So you will have to set the disabled attribute only when the condition is valid.

    something like:

    object attributes = null;
    if (!item.Selectable)
    {
        attributes = new { disabled = "disabled"};
    }
    @Html.CheckBoxFor(modelItem => item.Selected, attributes)
    
    0 讨论(0)
提交回复
热议问题