I have a list which I created in the controller:
var PayList = new[] {
new ListEntry { Id = 1, Name = "" },
new ListEntry { Id = 2, Name = "Yes" },
new ListEntry { Id = 3, Name = "No" }
};
ViewBag.PayList = new SelectList(PayList, "Id", "Name");
In the view I have the following:
@Html.DropDownList("Pay", new SelectList(ViewBag.PayList,"Id","Name"))
When I try to display it, it says the following: DataBinding: 'System.Web.Mvc.SelectListItem' does not contain a property with the name 'Id'. Not sure why this is not working.
Also how do I default a value to the select list. I like to default it to "Yes". I thought there was a way to do do this from the controller.
Your ViewBag.PayList
is already the type of SelectList
. I don't see a reason to create the SelectList
twice, so shouldn't it just be:
@Html.DropDownList("Pay", ViewBag.PayList)
or
@Html.DropDownList("Pay", ViewBag.PayList as SelectList)
(I don't ever use the ViewBag, so I'm not sure if your version is strongly typed).
Just use
@Html.DropDownList("Pay", ViewBag.PayList)
In your view
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With