Could you help me create a dropdown list in asp.net mvc 4?
I Have a ProjetoFuncionario class that is an associative class of \"Projeto\" and \"Funcionario\"
A drop down list is used for selecting a value from a list of possible options. Its not clear from you model, but assuming you want a view with drop downs to select a Projeto
and a Funcionario
, then create a view model to represent what you want to display and edit (What is a view model). Note this example is based on the model definitions from your previous question.
public class ProjetoFuncionarioVM
{
[Display(Name="Projeto")]
public long SelectedProjeto { get; set; }
[Display(Name="Funcionario")]
public long SelectedFuncionario { get; set; }
public SelectList ProjetoList { get; set; }
public SelectList FuncionarioList { get; set; }
}
Controller
public ActionResult Edit()
{
ProjetoFuncionarioVM model = new ProjetoFuncionarioVM();
model.SelectedProjeto = // if you want to preselect one of the options
ConfigureEditModel(model);
return View(model);
}
public ActionResult Edit(ProjetoFuncionarioVM model)
{
if (ModelState.IsValid)
{
ConfigureEditModel(model); // reassign the select lists
return View(model); // return the view to correct errors
}
// access properties of the view model, save and redirect
}
private void ConfigureEditModel(ProjetoFuncionarioVM model)
{
List<Projeto> projeto = // get the collection of projeto objects from the database
List<Funcionario> funcionario = // ditto for funcionario objects
// Assign select lists
model.ProjetoList = new SelectList(projeto, "id_Projeto", "nome_Projeto");
model.FuncionarioList = new SelectList(funcionario, "id_funcionario", "nom_funcionario");
}
View
@model ProjetoFuncionarioVM
@using (Html.BeginForm())
{
@Html.LabelFor(m => m.SelectedProjeto)
@Html.DropDownListForFor(m => m.SelectedProjeto, Model.ProjetoList, "Please select")
@Html.ValidationMessageFor(m => m.SelectedProjeto)
@Html.LabelFor(m => m.SelectedFuncionario)
@Html.DropDownListForFor(m => m.SelectedFuncionario, Model.FuncionarioList, "Please select")
@Html.ValidationMessageFor(m => m.SelectedFuncionario)
<input type="submit" value="Save" />
}
Refer also SelectList and DropDownListFor for various overloads of these methods
Check out this link. I would suggest adding a property to your view model for the dropdown list and just make sure you populate it before passing it to your view.