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.
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?
– Ryan Santos
@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.
– Leonel Sanches da Silva
Make it clearer, please.
– Ryan Santos
@Ryansantos I updated the answer.
– Leonel Sanches da Silva
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?
– Ryan Santos
@Ryansantos You don’t have to.
– Leonel Sanches da Silva