How to Create DropDownList in ASP.NET MVC 4

7

Could you help me create a DropDownList in MVC4?

I have the class ProjetoFuncionario which is an associative class of Projeto and Funcionario .

Should I create a class for DropDown?

I'm having a hard time creating a DropDownList . Are there any good tutorials or tips you can give me?

Thank you.

namespace Exercicio1.Models
{
    public class ProjetoFuncionario
    {
        public Projeto IdProjeto { get; set; }
        public Funcionario IdFuncionario { get; set; }

        public List<ProjetoFuncionario> listaProjetoFuncionario()
        {
            return new List<ProjetoFuncionario>();
        }
    }
}
    
asked by anonymous 15.11.2014 / 21:45

1 answer

8

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" })
    
15.11.2014 / 22:13