Persist in my database values passed by a DropDown in my html?

-1

I have a dropdownlist with all UF of Brazil. For example:

public IEnumerable<SelectListItem> ObterUF()
{
     return IncluirSelecioneNoDropDown(new List<SelectListItem>()
     {
                new SelectListItem()
                {
                    Value = "CE",
                    Text = "CE"
                }
     }.AsEnumerable<SelectListItem>());
}

How do I persist in my database the value passed by the list in my html?

    
asked by anonymous 20.11.2014 / 12:48

1 answer

1

You can create a class to be your Model that will contain the properties you want to persist and a property of type list for the user to select the UF like this:

public class SeuCadastroViewModel
{
    public SeuCadastroViewModel(IEnumerable<SelectListItem> listaDeUFs)
    {
        ListaUFs = listaDeUFs;
    }

    //Propriedades do cadastro
    public int ID { get; set; }

    //Lista de UFs
    public int IdUFSelecionado { get; set; }
    public IEnumerable<SelectListItem> ListaUFs { get; set; }   

}

In the Controller you can get a list of your UFs and pass it to your Model , which will finally fill the list.

public class SeuController: Controller
{
    public ActionResult Create()
    {
        //Recupera uma lista de UFs
        var listaDeUFs = ObterUF();
        return View(new SeuCadastroViewModel(listaDeUFs));
    }

    [HttpPost]
    public ActionResult Create(SeuCadastroViewModel seuCadastroViewModel)
    {
        //Recupera o UF selecionado e salva no banco de dados
        var uf = ObterUFporId(seuCadastroViewModel.IdUFSelecionado);
        ...
    }
}

In your View you could render DropDownListFor like this:

@Html.DropDownListFor(model => model.IdUFSelecionado, Model.ListaUFs)
    
20.11.2014 / 13:11