Reputation: 14280
How can I write code below with a HTML helper?
<select name="CountryId">
@foreach (var c in ViewBag.Counties) {
<option value="@c.Id">@c.Name</option>
}
</select>
This code above will give the right html code in my browser. But if I use the HTML helper below the value attribute from the option tags are missing.
@Html.DropDownListFor(
model => model.CountryId,
new SelectList(ViewBag.Countries, "Name"),
new { htmlAttributes = new { @class = "form-control" } }
)
What's wrong in this code if you know that ViewBag.Counties
is an object from type List<Country>
and has the properties Name
(type of string) and CounrtyId
(type of int).
Upvotes: 1
Views: 2249
Reputation: 1375
Try this.your selectlist item class should be created in the parent class that is model class you are binding in the view page.
@Html.DropDownListFor(model => model.CountryId,new SelectList(ViewBag.Countries,"CountryID", "CountryName"),new {@class='form-control'})
Upvotes: 2