0

I have model :

 [Required(ErrorMessage = "*")
 public bool RecordingPersonalData{ get; set; }

My view:

@Html.CheckBoxFor(m => m.Register.RecordingPersonalData, new { @style = "position:absolute;opacitiy:0;" })
    @Html.ValidationMessageFor(m=>m.Register.RecordingPersonalData)

The main idea is if chekcbox is unchecked on submit, display error message, but I don't get anything..any idea?

ekad
  • 14,436
  • 26
  • 44
  • 46
None
  • 8,817
  • 26
  • 96
  • 171
  • Required won't work here, because the bool will either be true or false. You will have to create your own Attribute: http://stackoverflow.com/questions/4730183/mvc-model-require-true – Dawood Awan May 18 '15 at 09:31
  • A `boolean` property only has 2 values (`true` or `false`) and `@Html.CheckBoxFor()` generates a checkbox with `value="true"` and a hidden input with `value="false"` therefore `RecordingPersonalData` always has a value (your `[Required]` attribute is a bit pointless) –  May 18 '15 at 09:32
  • you need to implement custom validator for bool :http://blog.degree.no/2012/03/validation-of-required-checkbox-in-asp-net-mvc/ – Ehsan Sajjad May 18 '15 at 09:32
  • 1
    also see this working example:http://www.jasonwatmore.com/post/2013/10/16/ASPNET-MVC-Required-Checkbox-with-Data-Annotations.aspx – Ehsan Sajjad May 18 '15 at 09:33

1 Answers1

0

If a checkbox is required then it is a redundant control. You could either use a set of radio buttons (Yes/no/not known) linked to integer/enum values or remove the control altogether as I assume it is there to remind the user to enter other data.

You might be better served refining your model.

Peter Smith
  • 5,528
  • 8
  • 51
  • 77