Doubt with ViewBag, loading information for editing

0

I'm having an error, when I go to make a registration, I loaded the information this way:

//lista 
var tbuscarCategoria = new CadastroCategoriaAplicacao();
var listarCategoria = tbuscarCategoria.ListarTodos();
ViewBag.Categoria = new SelectList(listarCategoria, "IDCATEGORIA", "DESCRICAO");

In the registry edit, I need to select the category that is in the client registry, at this point I have an error:

    public ActionResult AlteraRegistro(int id)
        {
            if (Session["id"] == null)
            {
                return RedirectToAction("Index", "Home");
            }

            try
            {

                var tbuscar = new CadastroClienteAplicacao();
                TB_CLIENTE tbCliente = tbuscar.ListarPorID(id);

                //lista 
                var tbuscarCategoria = new CadastroCategoriaAplicacao();
                var listarCategoria = tbuscarCategoria.ListarTodos();
                ViewBag.Categoria = new SelectList(listarCategoria, "IDCATEGORIA", "DESCRICAO",tbCliente.tbIDCATEGORIA.IDCATEGORIA);

                return View(tbCliente);

            }
            catch (Exception)
            {
                TempData["Erro"] = "Erro ao Alterar Registro.";
                return RedirectToAction("ListarRegistro", "CadastroCliente");
            }
        }
    
asked by anonymous 17.06.2016 / 06:10

1 answer

0

The problem was occurring because in my in class I had an integration with the category table:

        [Display(Name = "Categoría:")]
        [Required(ErrorMessage = "Campo Obrigatório")]
        public TB_CATEGORIA tbIDCATEGORIA { get; set; }

I made the change to get only the IDCATEGORIA of the cadastre itself:

        [Display(Name = "Categoría:")]
        [Required(ErrorMessage = "Campo Obrigatório")]
        public int IDCATEGORIA { get; set; }

To load the data in the view record I have:

            var tbuscarCategoria = new CadastroCategoriaAplicacao();
            var listarCategoria = tbuscarCategoria.ListarTodos();
            ViewBag.Categoria = new SelectList(listarCategoria, "IDCATEGORIA", "DESCRICAO");

In the view

            <div class="col-md-3 form-group">
                @Html.LabelFor(x => x.IDCATEGORIA)
                @Html.DropDownListFor(x => x.IDCATEGORIA, ViewBag.Categoria as SelectList, new { @class = "form-control" })
                @Html.ValidationMessageFor(x => x.IDCATEGORIA)
            </div>

To load the data in the registry edit I have:

                var tbuscar = new CadastroClienteAplicacao();
                TB_CLIENTE tbCliente = tbuscar.ListarPorID(id);

                //lista 
                var tbuscarCategoria = new CadastroCategoriaAplicacao();
                var listarCategoria = tbuscarCategoria.ListarTodos();
                ViewBag.Categoria = new SelectList(listarCategoria, "IDCATEGORIA", "DESCRICAO", tbCliente.IDCATEGORIA);

This solved the problem.

    
17.06.2016 / 17:23