I'm developing a registration system using MVC5
with DAO
, however there were some doubts that I could not solve.
I have a table where I register Projects and another where the types of Projects are:
Table: Projects
Fields:
- ProjProjectId
- ProjName
- ProjTipoId
Table: TypeType
Fields:
- ProjTipoId
- ProjectName
I need to show in my view
a DropDownList
with all the projects for the user to select (in the register). And I also need to bring these Project Types in the Edit Project page so that the previously entered value is selected.
After some research I managed to make it work, but not the way I would like the code to look like this:
(ProjectController)
//Controller GET: Projeto/Edit/5
public ActionResult Editar(int id)
{
//Pesquisar projeto selecionado
ProjetoDAO proj_dao = new ProjetoDAO();
Projeto proj = proj_dao.listById(id);
//Pesquisar todos os TIPOS de projetos
ProjetoTipoDAO proj_tipo_dao = new ProjetoTipoDAO();
List<ProjetoTipo> lista_projetotipo = proj_tipo_dao.ListAll();
//Lista de SelectListItem
List<SelectListItem> lista_ddl = new List<SelectListItem>();
//Percorrer lista de Tipos de Projetos e adicionar na lista de SelectListItem
bool selected = false;
foreach (var item in lista_projetotipo)
{
//Checar se é o ID selecionado
selected = (proj.ProjTipoId.ToString().Equals(item.ProjTipoId.ToString()));
//Adicionar item na lista
lista_ddl.Add(
new SelectListItem()
{
Text = item.ProjTipoNome,
Value = item.ProjTipoId,
Selected = selected
});
}
//Enviando a lista de Tipos de Projetos para a view através de ViewBag
ViewBag.ListaTiposProjeto = lista_ddl;
}
(Edit.cshtml)
<div class="row">
<div class="form-group">
<div class="col-md-2">
@Html.LabelFor(model => model.ProjTipo,
new { @class = "control-label" })
</div>
<div class="col-md-10">
@Html.DropDownList("ListaTiposProjeto", null,
"Selecione um item", new { @class = "form-control" })
</div>
</div>
</div>
In this way, I can display the data in DropDownList
and also bring it selected on the edit page, but I can not use ModelState
to validate the form.
- How would I do the same thing using
@Html.DropDownListFor<>
? - That would be the way, because I followed some tutorials and did not work!