Error when running Dropdownlist in ASP.Net MVC

0

I'm having the following error at runtime:

System.InvalidOperationException: 'There is no ViewData item of type' IEnumerable 'that has the' SexID 'key.'

Follow the code below:

Model:

    [Required(ErrorMessage = "O campo sexo é obrigatório!")]
    public int SexoID { get; set; }

Controller:

 public ActionResult DropDown()
    {
        var model = new CadastroModel();

        ViewBag.Sexo = new List<SelectListItem>
        {
            new SelectListItem { Text = "Selecione", Value="", Selected = true},
            new SelectListItem { Text = "Masculino", Value="1"},
            new SelectListItem { Text = "Feminino", Value="2"},

        };

        return View(CadastrarUsuario);
    }

    [HttpPost]
    public ActionResult DropDown(CadastroModel CadastrarUsuario)
    {
        if (ModelState.IsValid)
        {

            return View(CadastrarUsuario);
        }



        ViewBag.Sexo = new List<SelectListItem>
        {
            new SelectListItem { Text = "Selecione", Value="", Selected = true},
            new SelectListItem { Text = "Masculino", Value="1"},
            new SelectListItem { Text = "Feminino", Value="2"},

        };

        return View(CadastrarUsuario);
    }

View:

<div class="form-group col-md-3">
            <div class="editor-label col-md-3">
                @Html.LabelFor(m => m.SexoID)

                <div class="col-md-3">
                    @Html.DropDownListFor(e => e.SexoID, ViewBag.Sexo as IEnumerable<SelectListItem>, "Selecione")
                    @Html.ValidationMessageFor(e => e.SexoID)
                </div>
            </div>
        </div>
    
asked by anonymous 29.05.2018 / 03:53

1 answer

0

The error occurs because in your sex list ( new SelectListItem { Text = "Masculino", Value="1"} ) does not have the SexoId field, however in your DropDownList(@Html.DropDownListFor(e => e.SexoID...)) you indicate that you will have the property with that name.

At the moment I think of two ways to solve this problem

1st:

Instead of using DropDownListFor use DropDownList , so it will not "force" you to have a property with that name in the list

@Html.DropDownList("SexoId", ViewBag.Sexo as IEnumerable<SelectListItem>, "Selecione")

2nd:

Create a class (containing the SexoId property ), a list of that class, and mount DropDownList

public class Sexo
{
    public int SexoId { get; set; }
    public string Texto { get; set; }
}

List<Sexo> sexos = new List<Sexo>{
    new Sexo{ SexoId=1, Texto = "Masculino" },
    new Sexo{ SexoId=2, Texto = "Feminino" }
};

ViewBag.Sexo = new SelectList(sexos, "SexoId", "Texto");

@Html.DropDownListFor(e=> e.SexoId, (SelectList)ViewBag.Sexo, "Selecione")
    
29.05.2018 / 04:54