Home > Software engineering >  How to stop FormMethod.Post when ModelState.IsValid = False
How to stop FormMethod.Post when ModelState.IsValid = False

Time:12-30

I noticed that my error handling was not working.

I have this Razor code on Page1.cshtml:

@using (Html.BeginForm("Page2", "Page1", FormMethod.Post))

In the Page1Controller.cs file, I have:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Page2(GenericModel model)
{
    if (ModelState.IsValid)
    {

If ModelState.IsValid = false, the FormMethod.Post still redirects to Page2 with the errors.

Is there a way to stop this flow if the ModelState is NOT Valid?

CodePudding user response:

Is there a way to stop this flow if the ModelState is NOT Valid?

Well, In this scenario we have two options in hand, either use client side validation or use middleware/actionfilter. This would check the state before reaching to the controller and return expected validation message to browser.

Middleware/Action Filter:

public class ValidateModelStateAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                context.Result = new BadRequestObjectResult(context.ModelState);
            }
        }
    }

Program.cs:

builder.Services.AddControllersWithViews(options =>
{
    options.Filters.Add<ValidateModelStateAttribute>();
});

Startup.cs:

services.AddMvc(validateModelState=> {
        validateModelState.Filters.Add(new ValidateModelStateAttribute());
       });

Model:

public class GenericModel
    {

       
        public string Id { get; set; }
        [Required(ErrorMessage = "A valid Name is required.")]
        public string Name { get; set; }
    }

Note: Above ErrorMessage would shown while the post request submitted with invalid model and no longer controller would be invocked. It would implied to all controller and model validateion.

Output:

enter image description here

CodePudding user response:

As it turns out, in addition to the steps provided in most online instructions, the following section must be called on the Razor page (*.cshtml):

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

After I included it at the bottom of the page, the validation magically stops Page1 from POST-ing and displays the error(s).

  • Related