Validation without "Modelstate.isValid"

Asked

Viewed 474 times

5

I have the following scenario:

    [HttpPost]
    public PartialViewResult Create(string dados)
    {
        var clienteViewModel = DeserializeJson<ClienteViewModel>(dados);
        if (ModelState.IsValid) { } // Não têm como validar.
        ...
    }

I receive the json and convert to the Clienteviewmodel object, but this way it is not possible to validate with the "Modelstate.isValid" because it validates the model that is in the parameter.

I don’t want to have to send the form normally to Action and in its parameter put Clienteviewmodel instead of "string data (json)" because this causes the whole page to be loaded, and I don’t want that.

Is there any way to validate Viewmodel that way?

2 answers

6

The ideal is to validate by ModelState, as shown in the response of @Eduardosampaio. But you can validate otherwise.

To do the validation, you need to use the Validationcontext class.

An example would be this:

var clienteViewModel = DeserializeJson<ClienteViewModel>(dados);
List<ValidationResult> restuls = new List<ValidationResult>();
ValidationContext context = new ValidationContext(clienteViewModel, null, null);


bool isValid = Validator.TryValidateObject(clienteViewModel, context, restuls, true);

if (!isValid)
{
    foreach (var validationResult in restuls)
    {
        var pause = true;
    }
}

Another option would be to use theDataannotations Validator.

Just install the package with the following command:

Install-Package Dataannotationsvalidator

And to use, just do the following:

var clienteViewModel = DeserializeJson<ClienteViewModel>(dados);
var validator = new DataAnnotationsValidator.DataAnnotationsValidator();
var validationResults = new List<ValidationResult>();

var isValid = validator.TryValidateObjectRecursive(clienteViewModel , validationResults);

The original package code you can see in this reply the author. But in short, it only uses the ValidationContext in the "same way".

If you want to know more, you can look this article and this answer.

4


you can’t do it this way below: if the attributes are exactly the same name as the viewmodel it can receive all the parameters and does not need to deserialize.

   [HttpPost]
    public PartialViewResult Create(ClienteViewModel model)
    {            
        if (ModelState.IsValid) { }
        ...
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.