TemplateState Validation Error

0

I want to return the validation errors of my model. I just get an error message when I try to register.

  

System.Linq.Enumerable + WhereEnumerableIterator'1 [System.Web.Mvc.ModelErrorCollection]

I'm putting validation in 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 ViewModel , only 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);
    
asked by anonymous 08.06.2017 / 01:51

2 answers

2

This is wrong here, you can not do it this way:

string erros = ModelState.Select(x => x.Value.Errors).Where(y => y.Count() > 0).ToString();

You are transforming a collection into a string and when you do this the string that is returned is

  

System.Linq.Enumerable + WhereEnumerableIterator'1 [System.Web.Mvc.ModelErrorCollection]

Solution

The correct thing is that you turn the collection items into string, a possible solution would be:

Whereas x.Value.Errors is a collection

string erros =string.Join(", ",ModelState.Select(x => x.Value.Errors).Where(y => y.Count() > 0).SelectAll(z => z.ToArray() ));

So you gather all the items in the collection and transforms them into a comma-separated string.

    
08.06.2017 / 02:11
0

I used it with foreach and it worked like this:

var ListaErros = new List<string>();
                foreach (var values in ModelState.Values)
                {
                    foreach (var erros in values.Errors)
                    {
                        ListaErros.Add(erros.ErrorMessage);
                    }
                }
    
09.06.2017 / 01:34