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

Asked

Viewed 74 times

-1

I have a dropdownlist with all the states 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?

1 answer

1

You can create a class to be your own Model which will contain the properties you want to persist and a list type property 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 Controller you can get a list of your Ufs and pass it to your Model, who will finally fill in 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);
        ...
    }
}

Already in his View you could render the Dropdownlistfor like this:

@Html.DropDownListFor(model => model.IdUFSelecionado, Model.ListaUFs)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.