-1

I'm new to MVC and trying to do a simple application form with a check box to accept the terms. I cant understand why my error message isnt showing. This is my .cshtml

<div class="form-row">
    <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>

my ViewModel

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

Controller

[AcceptVerbs(HttpVerbs.Post)]
    public ActionResult AppForm(AppFormViewModel App)
    {

        if (ModelState.IsValid)
        {
            return View();
        }

        return View(App);
    }

When I click the button, the page refreshes with no changes. While debugging, the Model.State is false, so I really cant understand why nothing is happening. Does anyone have any ideas?

Chillin'
  • 172
  • 1
  • 15
  • Any help would be appreciated!!! – Chillin' May 12 '17 at 14:17
  • Please note that the model-view-controller tag is for questions about the pattern. There is a specific tag for the ASP.NET-MVC implementation. –  May 12 '17 at 23:04

1 Answers1

0

Being a value type, your bool has a default value of false - this is a value and therefore does not get recognised as "missing". You will need to validate that the value is true, rather than being required.

You could look at this question for a way to achieve this.

Community
  • 1
  • 1
Oliver
  • 8,794
  • 2
  • 40
  • 60
  • Oh ok I didnt see it like that. Is that why the Model.State was showing as false, because the checkbox was not checked therefor is false? – Chillin' May 12 '17 at 14:40
  • @user6950100 yes that's about right, although even if there was no form control to bind with it would still come through as false. Basically, using `RequiredAttribute` won't give you what you need. – Oliver May 12 '17 at 14:43