I have a form with a single textbox. The field bound to that textbox is required.
When I post the form with that textbox empty I get ModelState.IsValid = False as expected. But, the form still fires the data-ajax-success.
Relevant .cshtml
<form method="post" asp-page-handler="ProductAliasCreate" data-ajax="true" data-ajax-method="post" data-ajax-success="refreshPartial('GetAliases', 'product-aliases-container')" data-ajax-failure="handleError">
Relevant .cshtml.cs
public async Task<IActionResult> OnPostProductAliasCreateAsync()
{
if (!ModelState.IsValid || _context.ProductAliases == null || ProductAlias == null)
{
return Page();
}
_context.ProductAliases.Add(ProductAlias);
await _context.SaveChangesAsync();
return Page();
}
It's hitting that first return Page(); inside that Isvalid check.
How do I prevent the data-ajax-success callback from firing when ModelState.IsValid = false?
Note: I previously had the refreshPartial callback in the data-ajax-complete with the same result...so I moved it to data-ajax-success thinking that'd be the solution to this issue.

Return Page() would always return response with 200 statue code in your senaro,if you want fire
data-ajax-successwhen modelstate is invalid,you should return response with 400 statuecodeA minimal example,hopes help:
PageModel:
Page:
Result:
Update based on your comment:
If you've passed client validation(in my case,null check) and got model state error on server(for example,duplicated Name)
If you want to show the errors ,you have to refresh the page yourself due to ajax call
My solution:
create a filter:
PageModel:
Page:
Result: