Error running Dropdownlist on ASP.Net MVC

Asked

Viewed 843 times

1

I’m having the following error when turning:

System.Invalidoperationexception: 'There is no 'Ienumerable' Viewdata item that has the 'Sexoid' key'.'

Follows 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>

1 answer

1

The error occurs because in your sex list(new SelectListItem { Text = "Masculino", Value="1"}) doesn’t have the field Sexoid, however in its 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 the DropDownListFor use the DropDownList, so you will not "force" that you have a property with that name in the list

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

2nd:

Create a class(that contains the property Sexoid), a list of that class and build the 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")

Browser other questions tagged

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