0
I am wanting to return the validation errors of my model. Only I get an error message when I try to register.
System.Linq.Enumerable+Whereenumerableiterator`1[System.Web.Mvc.Modelerrorcollection]
I’m putting the validation on controller:
public async Task<ActionResult> Create(ClienteViewModel viewmodel)
{
if (ModelState.IsValid)
{
db.Set<Pessoa>().Add(viewmodel.Pessoa);
if (viewmodel.Cliente.TipoPessoa.Equals(Models.Enum.TipoPessoa.Juridica))
{
db.Set<PessoaJuridica>().Add(viewmodel.PessoaJuridica);
}
else {
db.Set<PessoaFisica>().Add(viewmodel.PessoaFisica);
}
db.Cliente.Add(viewmodel.Cliente);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
else {
string erros = ModelState.Select(x => x.Value.Errors).Where(y => y.Count() > 0).ToString();
ModelState.AddModelError("", erros);
}
// ViewBag.PessoaId = new SelectList(db.Pessoa, "PessoaId", "Nome", cliente.PessoaId);
return View(viewmodel);
}
In the Viewmodel only stance the classes Pessoa
, PessoaJuridica
and Fisica
.
EDIT
The error happens on this line where return to view.
string erros = ModelState.Select(x => x.Value.Errors).Where(y => y.Count() > 0).ToString();
ModelState.AddModelError("", erros);
Do you have a complete error? It happens at runtime?
– Jéf Bueno
On which line is this error generated? No
if (ModelState.IsValid)
?– Rodolpho Sa
I added the line, the error is stored inside the error variable.
– Aprendiz