DropDownListFor with ViewBag and Dictonary returning null value

0

I would like everyone's help to help with the following problem:

Theerrorhappenswhenheisstilldoingthefieldvalidations.

Controller:

publicActionResultCreate(){varvEmpresas=newDictionary<string,string>();vEmpresas.Add("Matriz", "Matriz");
        vEmpresas.Add("Filial1", "Filial1");
        vEmpresas.Add("Filial2", "Filial2");
        ViewBag.Empresas = vEmpresas;

        return View(model: new Suporte { Empresa = "Matriz"});
    }


    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "Codigo,DataInicio,DescProblema,Empresa,Solicitante,Atendente,CodAtendimento,CodChamado,Solucao,Status")] Suporte suporte)
    {
        if (ModelState.IsValid)
        {
            db.SuporteAts.Add(suporte);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(suporte);
    }

View:

    <div class="form-group">
        @Html.LabelFor(model => model.Empresa, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.Empresa, new SelectList(ViewBag.Empresas, "key", "value",selectedValue: null) , new { @class = "form-control" } )
            @Html.ValidationMessageFor(model => model.Empresa, "", new { @class = "text-danger" })
        </div>
    </div>
    
asked by anonymous 16.08.2018 / 21:55

2 answers

2

As I said in the comments of the other answer, the problem occurs when it returns to View after data validation the ViewBag is not loaded with the data.

In the code below, I extract the load from ViewBag on a method and I called it on two Actions

public ActionResult Create()
{
    CarregaDropDownList();
    return View(model: new Suporte { Empresa = "Matriz"});
}


[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Codigo,DataInicio,DescProblema,Empresa,Solicitante,Atendente,CodAtendimento,CodChamado,Solucao,Status")] Suporte suporte)
{
    CarregaDropDownList();
    if (ModelState.IsValid)
    {
        db.SuporteAts.Add(suporte);
        db.SaveChanges();
        return RedirectToAction("Index");
    }   
    return View(suporte);
}

public void CarregaDropDownList()
{
    var vEmpresas = new Dictionary<string, string>();
    vEmpresas.Add("Matriz", "Matriz");
    vEmpresas.Add("Filial1", "Filial1");
    vEmpresas.Add("Filial2", "Filial2");
    ViewBag.Empresas = vEmpresas;
}
    
17.08.2018 / 15:33
1

Try as follows: Create a class called Company

public string codigo_empresa{ get; set; }
public string nome_empresa{ get; set; }

And just below the following:

public List<Empresas> ListaEmpresas(){

 List<Empresa> empresas= new List<Empresa>();
 empresas.Add(new Empresa
        {
            codigo_empresa = "Matriz",
            nome_empresa= "Matriz"
        });
  empresas.Add(new Empresa
        {
            cod_setor = "Filial1",
            nome_setor = "Filial1"
        });
  empresas.Add(new Empresa
        {
            cod_setor = "Filial2",
            nome_setor = "Filial2"
        });
 return empresas;

}

And in the controller, you do this:

    public ActionResult Create()
    {
         ViewBag.Empresas = new SelectList(
            new Empresa().ListaEmpresas(), "codigo_empresa","nome_empresa");
        return View(model: new Suporte { Empresa = "Matriz"});
    }


    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "Codigo,DataInicio,DescProblema,Empresa,Solicitante,Atendente,CodAtendimento,CodChamado,Solucao,Status")] Suporte suporte)
    {
        if (ModelState.IsValid)
        {
            db.SuporteAts.Add(suporte);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(suporte);
    }

And the dropdown looks like this:

 @Html.DropDownListFor(model => model.empresa, (IEnumerable<SelectListItem>)ViewBag.Empresas, new { @class = "form-control"})
    
17.08.2018 / 13:19