3
I am developing a registration system using MVC5
with DAO
, but there were some doubts that I could not resolve.
I have a table where I register Projects and another one where the types of Projects are:
Table: Projects
Campos:
- Projectoid
- Projectionist
- Projectoid
Table: Projectotpo
Campos:
- Projectoid
- Projectonome
I need to show in my view
one DropDownList
with all projects for the user to select (in the registration). And I also need to bring these Project Types in the Edit Project page, so that the previously registered value is selected.
After some researches I was able to make it work, but not in the way I would like that the code is currently like this:
(Projectocontroller)
//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>
That way, I can display the data on DropDownList
and also bring it selected on the edit page, but I can not use the ModelState
to validate the form.
- How I would do the same thing using the
@Html.DropDownListFor<>
? - This would be the way? , because I followed some tutorials and did not work!
Thank you, it worked the way I needed it.
– Rafael