0

I'm creating multiple check boxes but I would like one to be automatically checked and unable to be unchecked by a user. Below is the base code for my check boxes.

<div class="form-control">
                    <div class="row"><span>1: @Html.CheckBoxFor(m => m.1, new {form = "mainForm"})</span></div>
                    <div class="row"><span>2: @Html.CheckBoxFor(m => m.2, new {form = "mainForm"})</span></div>
                    <div class="row"><span>3: @Html.CheckBoxFor(m => m.3, new {form = "mainForm"})</span></div>
                    <div class="row"><span>4: @Html.CheckBoxFor(m => m.4, new {form = "mainForm"})</span></div>
</div>

I tried adjusting my code to pass along several attributes to the html element like so but it didn't work.

<div class="form-control">
                    <div class="row"><span>1: @Html.CheckBoxFor(m => m.1, new {form = "mainForm"})</span></div>
                    <div class="row"><span>2: @Html.CheckBoxFor(m => m.2, new {form = "mainForm", checked = "true", value = "true"})</span></div>
                    <div class="row"><span>3: @Html.CheckBoxFor(m => m.3, new {form = "mainForm"})</span></div>
                    <div class="row"><span>4: @Html.CheckBoxFor(m => m.4, new {form = "mainForm"})</span></div>
</div>

I would like to avoid using jQuery here if possible as I can't get my jQuery functions to load from my partial view files.

WebDevver
  • 13
  • 3
  • Duplicate: https://stackoverflow.com/questions/16435448/how-to-set-a-checkbox-by-default-checked-in-asp-net-mvc – Anthony G. Sep 22 '22 at 22:22
  • @AnthonyG. I don't think that if you set the value in the controller, as that solution says, it protects the checkbox from being unchecked. – WebDevver Sep 22 '22 at 22:27
  • Correct. It will default to checked, but user would be able to change it. To prevent that behavior you could make the checkbox read only or disabled, but user could still edit source to enable and send it to server-side so you would have to guard against it (At which point you are just hard coding property). If you want to prevent user from changing that value, just don't include it on the UI. Are you looking for Radio button behavior? Single selected value from options? – Anthony G. Sep 22 '22 at 22:34
  • For user clarity it is preferred that the checkbox look the same as the others even if it is essentially hard coded. Read only will be acceptable despite the fact that the value could be adjusted on the client side. I can't seem to get the readonly attribute to work despite the fact that I can see it on the element with inspect element but that can probably be resolved. – WebDevver Sep 22 '22 at 22:45

0 Answers0