Return Controller List to View

2

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>
    
asked by anonymous 09.06.2017 / 01:57

1 answer

2

For this case (Listing errors), ValidationSummary is the best option.

To use it, in your View just add this where the Error Summary should appear:

@Html.ValidationSummary(true, "", new { @class = "text-danger" })

In your code it is possible to notice that you already have the ValidationSummary then possibly your question is on how to add items to it. To do this, on your Controller, whenever an error occurs, add it to the summary using ModelState.AddModelError ". Example:

if (ModelState.IsValid) 
{ 
    if(x == y //Uma condição qualquer)
    {
        ModelState.AddModelError(string.Empty, "O x é igual a y!");

        return View(suaView);
    }
}

Other options for communicating Controller > View

All content below I am putting because of your doubts on how to send Controller information to the View and due to the question that is in the title:

  

Return Controller List to View

You can use TempData , ViewBag or ViewData . In short, the difference between them is that TempData has a longer duration time, while ViewBag and ViewData are similar, and the life of these two is basically the sending of the Controller to the View , after that it already becomes null.

Example with TempData

public ActionResult Index()
{
    var ListaErros = new List<string>();
    ListaErros.Add("Erro 1");
    ListaErros.Add("Erro 2");

    TempData["erros"] = ListaErros;

    return View();
}

In your View :

@{
    foreach(string erro in TempData["erros"]  as List<string>)
    {
        Html.TextBox(erro);
    }
}

Example with ViewBag

public ActionResult Index()
{
    var ListaErros = new List<string>();
    ListaErros.Add("Erro 1");
    ListaErros.Add("Erro 2");

    ViewBag.ListaErros= ListaErros;

    return View();
}

In your View :

@{
    foreach (string erro in ViewBag.ListaErros)
    {
        Html.TextBox(erro);
    }
}

Example with ViewData

public ActionResult Index()
{
    var ListaErros = new List<string>();
    ListaErros.Add("Erro 1");
    ListaErros.Add("Erro 2");

    ViewData["erros"] = ListaErros;

    return View();
}

In your View :

@{
    foreach(string erro in ViewData["erros"]  as List<string>)
    {
        Html.TextBox(erro);
    }
}

Another difference you may notice in the examples is that TempData and ViewData requires a TypeCasting ( TempData["erros"] as List<string> , for example) while ViewBag is not required.

    
09.06.2017 / 03:58