user2232273 user2232273 - 27 days ago 9
C# Question

DropDownList in MVC 4 with Razor

I'm trying to create a

DropDownList
in a view.

Can someone can help with this?

Normal HTML5 code:

<select id="dropdowntipo">
<option value="Exemplo1">Exemplo1</option>
<option value="Exemplo2">Exemplo2</option>
<option value="Exemplo3">Exemplo3</option>
</select>


I tried this:

@{
var listItems = new List<ListItem> { new ListItem { Text = "Exemplo1", Value = "Exemplo1" }, new ListItem { Text = "Exemplo2", Value = "Exemplo2" }, new ListItem { Text = "Exemplo3", Value = "Exemplo3" } };
}

@Html.DropDownListFor(model => model.tipo, new SelectList(listItems), "-- Select Status --")

Answer
@{
   List<SelectListItem> listItems= new List<SelectListItem>();
   listItems.Add(new SelectListItem
        {
          Text = "Exemplo1",
          Value = "Exemplo1"
        });
   listItems.Add(new SelectListItem
        {
            Text = "Exemplo2",
            Value = "Exemplo2",
            Selected = true
        });
   listItems.Add(new SelectListItem
        {
            Text = "Exemplo3",
            Value = "Exemplo3"
        });
}

@Html.DropDownListFor(model => model.tipo, listItems, "-- Select Status --")
Comments