I am posting a form in an asp.net-mvc page. Here is my controller action:
public ActionResult UpdateData(MyFormObject entity)
{
bool isValid = IsValid(entity);
if (!isValid)
{
var firstError = ModelState.Values.SelectMany(v => v.Errors).First();
throw new HttpException(404, firstError.ErrorMessage);
}
return Json(BuildResult(entity));
}
Even thought the post passes all of my explicit validation logic, when i check ModelState I see errors. I am seeing errors in ModelState when any of my properties are empty. Here is my object:
public class MyFormObject
{
public int Id{ get; set; }
public int TestId{ get; set; }
public int OtherId{ get; set; }
}
and I am looking at Model.State and i see errors for any element in my object that is not populated.
If I change this to (NOTE: the “?”)
public class MyFormObject
{
public int? Id{ get; set; }
public int? TestId{ get; set; }
public int? OtherId{ get; set; }
}
then i no longer get any errors. Is there some default validation that is happening here that I am not setting. I am trying to figure out what is setting ModelState errors in the first case above.
As @Maxim V. Pavlov said, when you post, ASP.MVC engine will try to validate the model, ie its class, and based on class you cited as example, the properties don’t accepts a null or empty value, then it will throw an exception and ModelState will be invalid.
You can see more here @ Validating Model Data in an MVC Application and here ModelStateDictionary.IsValid Property