0

In my entity model I have a required attribute:

[Required]
public string Occupation { get; set; }

I have an OnPostAsync Method that returns the page if the user submits invalid information

if (!ModelState.IsValid)
{
  return Page();
}

If disable javascript (run server side validation) and submit a form with a blank Occupation field, I get the following error:

An unhandled exception has occurred while executing the request.
System.NullReferenceException: Object reference not set to an instance of an object.

If I instead return RedirectToPage(), everything is fine, but I don't get the error messages displayed on the client.

The official microsoft docs simply return Page(). Why I am I getting unhandled exceptions, and how can I preserve validation errors on the client while avoiding them?

I_A
  • 141
  • 9
  • tried a small app. works fine. unless you are using some property of some object (i.e. ViewBag) in cshtml which is set to null when returning Page() – Iqan Shaikh Sep 03 '20 at 22:47
  • Since you did not provide a detailed code, we are unable to determine what caused the problem. I suggest you provide us with reference to all the codes involved in this issue. – LouraQ Sep 04 '20 at 06:21

1 Answers1

0

Create your own custom validation and check for the field i.e if the field is blank or empty.

Documentation Link : https://docs.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-5.0 Refer this video : https://www.youtube.com/watch?v=o_AH2MGti0A