What is best way to display error message that all radio buttons must be selected in an ASP.NET Core MVC view?

202 Views Asked by At

I have a set of radio buttons in my ASP.NET Core MVC view. If "Submit" (save) is clicked without selecting ALL radio buttons, I want to display a message:

All radio buttons must be selected

in the @HTML.ValidationSummary at the top of my view.

What's the best way to achieve this please?

1

There are 1 best solutions below

1
Xinran Shen On

One of the most simplest method is using ViewBag instead of @HTML.ValidationSummary. @HTML.ValidationSummary will show all list of the error messages instead of custom error message by default, So you can try this simple demo:

<form method="post">        
    @ViewBag.Error
    <input type="radio"..../>
    ..........


</form>

controller

        [HttpPost]
        public IActionResult Index(TestModel model)
        {
            if (!ModelState.IsValid)
            {
                //set error message
                ViewBag.Error = "All radio buttons must be selected.";
                return View(model);
            }
              .......
           
        }

Then, when you don't select all radio buttons and submit the form, The error message will show, You can also add Css style to make it look the way you want.

enter image description here