I have controller
where I validate the information of ModelState
, I store the errors in a list.
I'd like to take this list and return it to my view. But I'm a beginner and I can not understand how I can do this, could I use ValidationSummary
to list? or use partial
for return within view
?
My 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
{ /*Lista que quero retornar para minha view*/
var ListaErros = new List<string>();
foreach (var values in ModelState.Values)
{
foreach (var erros in values.Errors)
{
ListaErros.Add(erros.ErrorMessage);
}
}
}
return View(viewmodel);
}
View
:
@model Sistema.ViewModels.ClienteViewModel
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Cliente</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Cliente.TipoPessoa, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EnumDropDownListFor(model => model.Cliente.TipoPessoa, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Cliente.TipoPessoa, "", new { @class = "text-danger" })
</div>
</div>