Search code examples
c#asp.net-mvcasp.net-corerazor

How to stop FormMethod.Post when ModelState.IsValid = False


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?


Solution

  • 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).