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 links the first two.
My first question is: How popular is DropDownList
with the values in the Genero table (Are the genres already stored in the database)? I got to do it this way:
In the Create Publication 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 'Genero' key
My second question:
How to get the id of what gender the user chose, so that he can insert it in the third table ( PublicacaoGenero
)?
Edit:
This is my controller responsible for creating the publication.
[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 do not know if I do it right, but that's how I usually do it.