Returning an error response in the case of a null model
asp.net-mvc, asp.net-mvc-3
Solution
Are you using mvc3 or web-api? your tags indicate you're using mvc but your opening sentence implies web-api. If using mvc3 you can use the following:
In your controller before your call to ModelState.IsValid add:
if (modelObj == null)
{
ModelState.Clear();
var blankModel = new MyClass();
TryValidateModel(blankModel);
return View("About", blankModel);
}
If you're using web-api and assuming you're using `System.ComponentModel.DataAnnotations` you can use the following:
ModelState.Clear();
var model = new MyClass();
var results = new List<ValidationResult>();
Validator.TryValidateObject(model, new ValidationContext(model, null, null),
results, true);
var modelState = new ModelStateDictionary();
foreach (var validationResult in results)
modelState.AddModelError(validationResult.MemberNames.ToArray()[0],
validationResult.ErrorMessage);
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, modelState);
Problem
In my ASP.NET MVC API application, I can return a helpful `ErrorResponse` if a few of my `Required` fields are missing: ``` return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); ``` ``` "Message": "The request is invalid.", "ModelState": { "myModel.FooA": [ "The FooA is required." ], "myModel.FooC": [ "The FooC property is required." ], "myModel.FooD": [ "The FooD property is required." ] } ``` However as this answer confirms, a NULL model will validate. As I don't allow this, how can I return an equally helpful error response stating all the values that are required? I know that I can manually add a ModelError for each property, but I suspect there may be a way that `CreateErrorResponse` can do this for me.