-1

I'm wanting a checkbox in my MVC project for an application form where you have to check the box at the end to say you agree to the terms and conditions. I am using

<div class="form">
    <div class="validation-container">@Html.ValidationMessageFor(m => m.HasAcceptedTerms)
   </div>
    <div class="label-container">@Html.LabelFor(m => m.HasAcceptedTerms)</div>
    <div class="form-control">@Html.EditorFor(m => m.HasAcceptedTerms)</div>
</div>

I am then using the property

 [Required(ErrorMessage = "You must indicate you have read the statements above before continuing")]
    [Display (Name = "Please tick to show you accept all the above statements")]
public bool? HasAcceptedTerms
    {
        get; set;
    }

However, this is now giving me a dropdown with three values: not set, true, false`.

How can I get this back to a checkbox?

By the way, it has to be a nullable bool otherwise the validation doesn't work because by default the checkbox will be unchecked meaning false which IS a value.

I want to be able to see a checkbox and the validation will prevent the person from continuing on the server side if the checkbox is not checked.

I also read you can do this by adding another DisplayTemplate but not sure if this would apply to me. Is that right?

Chillin'
  • 172
  • 1
  • 15

1 Answers1

1

A nullable bool has 3 states (true, false and null), but a check nox has only 2 states (on/off which translates to true and false) which is why a dropownlist is generated. You cannot use a checkbox for a nullable bool.

Create a custom validation attribute that implements IClientValidatable to validate that the value must be true and apply it to a public bool HasAcceptedTerms { get; set; } property (not nullable). Refer dazbradbury's answer to MVC Model require true for an example.

Community
  • 1
  • 1