DropDownList
requires a well defined Id. Your association does not have this ID. Also, your class is pretty much out of the box. Let's make some adjustments:
public class ProjetoFuncionario
{
[Key]
public int ProjetoFuncionarioId { get; set; }
public int ProjetoId { get; set; }
public int FuncionarioId { get; set; }
public virtual Projeto Projeto { get; set; }
public virtual Funcionario Funcionario { get; set; }
}
In the Entity Framework convention, the default framework for MVC4 data access, the naming convention asks Id to be a suffix, not a prefix, so I switched to FuncionarioId
, ProjetoId
, etc.
Another thing is that I put a primary key to the association. This ensures correct operation of DropDown
.
Also, note that there are the integer properties (which are the keys that will be written to the database) and the navigation properties (the classes with virtual
in front). Each has its function, which is not the same. The virtual
classes serve the Entity Framework automatically bring the database records to you.
Once this is done, the rest is simple. You may need to have an Action on Controller to bring this to you.
public ActionResult Index() {
var projetosFuncionario = contexto.ProjetoFuncionarios.Where(pf => pf.FuncionarioId == 1);
ViewBag.ProjetosFuncionario = projetosFuncionario.ToList();
return View();
}
I put the return inside a ViewBag
. ViewBags are dynamic objects used to send additional information to a View .
Finally, we get to View . To mount a DropDown, use the Razor @Html Helper:
@Html.DropDownListFor(model => model.ProjetoFuncionarioId,
((IEnumerable<ProjetoFuncionario>)ViewBag.ProjetosFuncionario).Select(option => new SelectListItem {
Text = option.Projeto.Nome + ", " + option.Funcionario.Nome,
Value = option.ProjetoFuncionarioId,
Selected = (Model != null) && (option.ProjetoFuncionarioId == Model.ProjetoFuncionarioId)
}), "Escolha uma opção...", new { @class = "form-control" })