Popular Dropdownlist and make Insert with the chosen value

Asked

Viewed 805 times

1

In my DB I have 3 tables:

- Genero(IdGenero,Genero,Descricao)
- Publicação(IdPublicacao, Titulo, Sinopse,IdUsuario) 
- PublicaçãoGenero(IdPublicacaoGenero,IdPublicacao,IdGenero)

This last one makes the connection between the first two.

My first question is, how popular the DropDownList with the values of the Genero table (The generos are already written in the bank)? I did it this way:

In Publish Action I put the following line

ViewBag.Genero = new SelectList(db.Genero, "IdGenero", "Genero1", pg.IdPublicacao);

And in the view I did so:

@Html.DropDownList("Genero", ViewBag.Genero as SelectList, "Selecione um Genero")

However, I get the following error:

There is no Viewdata item of type 'Ienumerable' that has the key 'Genero'

My second doubt:

How to get the id of which genre the user chose, to be able to do the Insert in the third table (PublicacaoGenero)?

Edit:

This is my controller responsible for creating the post.

 [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult CriarPub(Publicacao pub)
        {
            PublicacaoGenero pg = new PublicacaoGenero();
            if (ModelState.IsValid)
            {
               ViewBag.Generos= db.Genero.ToList();
               pub.DtCriacao = DateTime.Now;
               db.Publicacao.Add(pub);
               pg.IdPublicacao = pub.IdPublicacao;
               pg.IdGenero = //aqui entraria o id do genero selecionado na dropdownlist
               db.SaveChanges();
               return RedirectToAction("Index", "Usuario");
            }
            return View(pub);
        }

I don’t know if I do it right, but this is how I usually do it.

1 answer

1


Try doing it the old-fashioned way. It’s a little more prolific, but it always works:

ViewBag.Generos = db.Genero.ToList();

View

@Html.DropDownListFor(model => model.GeneroId, ((IEnumerable<Genero>)ViewBag.Generos).Select(option => new SelectListItem {
    Text = option.Nome, 
    Value = option.Id.ToString(), 
    Selected = (Model != null) && (Model.GeneroId == option.Id)
}), "Selecione um Genero")

Controller, method POST

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult CriarPub(Publicacao pub)
    {
        if (ModelState.IsValid)
        {
           pub.DtCriacao = DateTime.Now;
           db.Publicacao.Add(pub);

           var pg = new PublicacaoGenero();

           // Esqueça essa construção. Esse tipo de atribuição pode provocar 
           // uma inclusão do registro em duplicidade.
           // pg.IdPublicacao = pub.IdPublicacao;
           // pg.IdGenero = //aqui entraria o id do genero selecionado na dropdownlist

           // Primeiro carregue o Genero no seu contexto e depois atribua o objeto
           // (não o Id) diretamente no objeto que está sendo criado.
           pg.Genero = db.Genero.SingleOrDefault(g => g.Id == pub.GeneroId);
           pg.Publicacao = pub;
           db.SaveChanges();
           return RedirectToAction("Index", "Usuario");
        }

        // A ViewBag é preenchida fora porque serve para o MVC refazer a View
        // caso ela seja inválida.
        ViewBag.Generos= db.Genero.ToList();
        return View(pub);
    }
  • Thanks. I managed to put it to work! But regarding my second question. How do I get this selected id and play on the bench?

  • @Ryansantos Depends on the logic of your Controller. As you did not put in the question how you intend to save your Model, I did not answer this part, but edit your question and leave a comment to me that I add the answer.

  • Make it clearer, please.

  • @Ryansantos I updated the answer.

  • I haven’t tested it yet because I’m on the street. But in my case, I created the Publicacaogenero table to allow the publication to have more than one gender (2 actually). Then in my publishing table I do not have the Generoid column and in the Publicacaogenero table I only left the ids even. It would be necessary to put the gender name in this table?

  • @Ryansantos You don’t have to.

Show 1 more comment

Browser other questions tagged

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