ModelState.AddModelError NullReferenceException (ASP.Net MVC Validations)



While trying to add validation errors to the ModelState using the AddModelError method, I was getting “NullReferenceException” run time errors.

After doing some research I found that if we follow the AddModelError with SetModelValue method as shown by the highlighted line below, the system doesn’t throw runtime NullReferenceException anymore.

ModelState.AddModelError(PropertyName, ErrorMessage);
ModelState.SetModelValue(PropertyName,ValueProvider[PropertyName]);

Comments