0

I have a radio button that is displaying a boolean field. When I submit the form data without checking the Radio button, it does not save as the field is required but it does not show a validation message. All the textboxes show the validation message, only the Radio button does not show validation message.

I have added:

  • [Required] to the field in the view model
  • @Html.ValidationMessageFor(m => m.isCurrent) in the view

However, it still does not show the error message.

Has anyone encountered a similar problem?

VIEWMODEL

    [Required]
    public bool? isCurrent { get; set; }

VIEW

<label type='checkbox'>
    Is this bus still a part of your fleet?
    <div>
        @Html.RadioButtonFor(m => m.isCurrent, true, new {id = "Yes"}) @Html.Label("Yes", "Yes")
        @Html.RadioButtonFor(m => m.isCurrent, false, new {id = "No"}) @Html.Label("No", "No")
        @Html.ValidationMessageFor(m => m.isCurrent)
    </div>
</label>
2
  • Do you have enabled client side validations and unobtrusive Javascript? Commented Aug 26, 2019 at 18:04
  • Also it good to check if razor pages are referencing validation js files. Commented Aug 26, 2019 at 18:06

2 Answers 2

1

I figured it out guys. I needed to wrap the Radio Buttons into a RadioButtonList.

@Html.RadioButtonFor(m => m.isCurrent, true, new {id = "Yes"}) @Html.Label("Yes", "Yes") @Html.RadioButtonFor(m => m.isCurrent, false, new {id = "No"}) @Html.Label("No", "No") @Html.ValidationMessageFor(m => m.isCurrent)

Sign up to request clarification or add additional context in comments.

1 Comment

I just offered you the same answer above, which was successfully builded and tested.
0

You need to add @Html.ValidationMessageFor. Also make sure you included jquery validation bundle or script at the bottom of the view. For instance:

@using (Html.BeginForm())
{
<label type='checkbox'>
    Is this bus still a part of your fleet?
    <div>
        @Html.RadioButtonFor(m => m.isCurrent, true, new { id = "Yes" }) @Html.Label("Yes", "Yes")
        @Html.RadioButtonFor(m => m.isCurrent, false, new { id = "No" }) @Html.Label("No", "No")
        @Html.ValidationMessageFor(m => m.isCurrent)
    </div>
    @Html.ValidationMessageFor(model => model.isCurrent, "", new { @class = "text-danger" })
</label>
    <input type="submit" value="send" />
}


@section scripts{
    @Scripts.Render("~/bundles/jqueryval")
}

Hope this helped :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.