Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC @Html.DropDownList Getting Error with SelectList in ViewBag

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.

like image 431
Nate Pet Avatar asked Dec 10 '22 04:12

Nate Pet


2 Answers

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).

like image 102
Erik Philips Avatar answered Jan 31 '23 06:01

Erik Philips


Just use

@Html.DropDownList("Pay", ViewBag.PayList)

In your view

like image 25
Rich O'Kelly Avatar answered Jan 31 '23 07:01

Rich O'Kelly