Return Controller List to View

Asked

Viewed 1,635 times

2

I have a controller where the information of the ModelState, store errors in a list.

I would like to take this list and return to my view. But I’m a beginner and I’m not getting to understand how I can do this, because I could use the ValidationSummary to list? or use a partial for the return within the 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>

1 answer

2

For this case (List 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 you can notice that you already have the Validationsummary then possibly your question is on how to add items to it. For that, in your Controller, whenever an error occurs, add to 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 to communicate Controller > View

All content below I’m putting due to your questions about how to send information from Controller to View and due to the question that is in the title:

Return Controller List to View

You can use the Tempdata, Viewbag or Viewdata. In short, the difference between them is that the Tempdata has a longer duration, while Viewbag and Viewdata are similar and the lifetime of these two is basically the sending of the Controller to the View, after that 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 his 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 his 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 his View:

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

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

Browser other questions tagged

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