Problem Initialize List for ASP.NET MVC validation

Asked

Viewed 72 times

2

I have an action that receives a user file.

[HttpPost]
public ActionResult UpdateFicheiro(FicheiroViewModel model)
{
   var listaDeFicheirosJaAnexados = servico.obtemficheirosJaAnexados();
   model.ficheirosJaAnexados = listaDeFicheirosJaAnexados.toList();

  if(!modelState.IsValid)
  {
     ModelState.AddModelError(string.Empty, "erro!");
     Return View(model);
  }
}

I check if the file already exists in the database, if the model exists it should be invalid and should display a message to the user saying that the file already exists. But that’s not what happens, because the listDeicheirosJaAnexados is always empty.

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
   if(listaDeFicheirosJaAnexados.contains(ficheiro)) 
      yield return new ValidationResult("ficheiro ja existe na base de dados");           
}

It seems that the Valide method only validates values it receives from the view. It is possible to fix this by passing the list of already attached files to the view, hiding it through css and then checking whether the file already exists in the list or not, but it does not seem to me the ideal solution.

I can also create a specific method and give you the list, but that would cause my controller to have 3 or 4 more lines of code, and honestly doesn’t seem the most correct way to solve the problem either.

What I really wanted was that when the Validate method was called, this method would already have access to the list without having to pass it through the view.

It is possible to do this ?

1 answer

1


Yes it is possible, but if you want to change the model you are receiving in the action you need to clean the ModelState and then revalidate again.

First it is important that your ViewModel implement the interface IValidatableObject

public class FicheiroViewModel : IValidatableObject
{
    public string Ficheiro { get; set; }
    public List<string> FicheirosJaAnexados { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {

        if (FicheirosJaAnexados != null && FicheirosJaAnexados.Contains(Ficheiro))
            yield return new ValidationResult("ficheiro ja existe na base de dados");
    }
}

Already in your controller, you need to use the ModelState.Clear(); and the TryValidateModel(model); to make your check.

[HttpPost]
public ActionResult UpdateFicheiro(FicheiroViewModel model)
{
    //Limpa o ModelState
    ModelState.Clear();

    //Manipulando a model
    var listaDeFicheirosJaAnexados = new List<string> { "teste"};
    model.FicheirosJaAnexados = listaDeFicheirosJaAnexados;

    //Executanto novamente a validação
    TryValidateModel(model);

    if (!ModelState.IsValid)       
        return View(model);

    // Inclua o seu código para regra de negócio e persistência.
    // ...
    // ...
    // ...

    //Destino da ActionResult no caso de sucesso
    return View("Index");

}

inserir a descrição da imagem aqui

Browser other questions tagged

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