The DropDownList
requires a well-defined Id. Your association does not have this Id. Also, your class is well out of the standard. 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 standard MVC4 data access framework, 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 the correct functioning of the DropDown
.
Still, note that there are integer properties (which are the keys that will be saved in the database) and navigation properties (the classes with the virtual
in front). Each one has its function, which is not the same. The classes virtual
serve Entity Framework to automatically bring the database records to you.
Done this, the rest is simple. Possibly you will need to have a Action in the 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 arrived at View. To mount a Dropdown, use Razor’s Helper @Html:
@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" })
What will appear on Dropdown?
– Leonel Sanches da Silva
The goal is to take the Idprojeto and Idfuncionaio and associate the two to fill a form using the dropdown.. I do not know if it was clear
– chewie
Okay, I’ll answer you.
– Leonel Sanches da Silva
Okay, I really appreciate your help.
– chewie