8

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.

Community
  • 1
  • 1
Jonathan
  • 13,947
  • 17
  • 94
  • 123
  • Hi @Jonathan. The above reference has a check if the model is not null. In case it is null, you can check below suggestion. – Imad Alazani Aug 15 '13 at 02:57
  • Can you call `Controller.ValidateModel(new MyClass())` if your object is null ? (nb, `ValidateModel` is a method on the `Controller` class). see http://stackoverflow.com/questions/6360087/manually-invoking-modelstate-validation – wal Aug 21 '13 at 13:42
  • there is no automatic way to achieve what you want. you require a custom model binder – Dave Alperovich Aug 21 '13 at 20:48
  • If `ModelState.IsValid()` were to test false on null values, then you would have errors immediately when the page loads, even before the user has begun to enter the form. actually a common issue in earlier validation frameworks. – Claies Aug 22 '13 at 01:06

1 Answers1

3

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);
Imad Alazani
  • 6,688
  • 7
  • 36
  • 58
wal
  • 17,409
  • 8
  • 74
  • 109