Validation model always fails

Asked

Viewed 672 times

1

I have the following models:

public class Local {
    [Key]
    public int Id { get; set; }

    public virtual Grupo Grupo { get; set; }
 }

public class Grupo
{
    [Key]
    public int Id { get; set; }

    [Required]
    public int? LocalId { get; set; }

    [Required]
    [StringLength(60)]
    public string Nome { get; set; }

    [ForeignKey("LocalId")]
    public virtual Local Local { get; set; }
}

In my controller before validating the model and adding to the database I inform the id of Local through a Session.

    [HttpPost]
    [ValidateAntiForgeryToken]
    public virtual ActionResult _Create(Grupo model)
    {
        model.LocalId = SessionContext.LocalSelecionado;

        if (ModelState.IsValid)
        {
            _service.Add(model);
            return RedirectToAction("_List");
        }

        return PartialView(model);
    }

Every time the validation fails saying that the LocalId is mandatory, and is, but I’m putting the value, at the breakpoint if I look at the locals of model is there the value and yet fails.

The only way I could do it is in the form by putting a field with name LocalId and bringing the value of the form so it also continues to recognize and the validation does not fail.

What can it be?

2 answers

2

You can use the following method: Modelstate.Clear(); to clean the model state and re-run the Modelstate.Isvalid.

Modelstate.Clear() performs a revalidation based on the currently populated model, already with its changes after sending the form, already in Action. Your method would look like this:

[HttpPost]
[ValidateAntiForgeryToken]
public virtual ActionResult _Create(Grupo model)
{
    model.LocalId = SessionContext.LocalSelecionado;

    ModelState.Clear();

    if (ModelState.IsValid)
    {
        _service.Add(model);
        return RedirectToAction("_List");
    }

    return PartialView(model);
}
  • Yeah, thanks for the tip!

  • I’m not sure about this, but if I’m not mistaken Clear will remove all errors found at validation time and so Isvalid will return true, however it will not revalidate the model

  • @Leandrogodoyrosa understand your concern, but in the tests I did, he revalidated, if there is still data that should be validated the errors are still returned.

1


This is because the Model is only validated before the Controller is executed, changing the model’s value will not change the value of the ModelState.IsValid

In your case you could take the [Required] of LocalId since it is not required to fill in this field by the user, it will be filled in by your program.

  • Thanks for the help. In case I could remove the required or just take the nullable from Localid. I like to use Required to generate the Migrations. Apart from the nullable Localid fails to insert into the bank and that’s exactly what I’m looking for.

  • I haven’t tested, but you can try changing the if (ModelState.IsValid) for if (TryValidateModel(model)), the detail ai is that it seems to me that this method validates only the object passed to it, if I understood correctly the functioning of it could happen for example it does not validate its class Local if she had any validation rules

  • Yes, I could also revalidate the model, but there’s no need in my case. With the required i Gero nullables in Migrations and if the form does not have the field and I do not manually insert in the automatic screen tests will fail, if it fails is because in the controller I forgot to set the id, this is what I needed!

Browser other questions tagged

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