0

I have a table called Riders, containing information about horse riders. I want to use FirstName and 'ID' columns to populate a select dropdown. I've been bashing my head with this for a good 3 hours now and I get the same result - A dropdown list with same amount of options as my table recors, with text: System.Web.Mvc.SelectListItem. I pass the values to the View like this:

 ViewBag.Riders = new SelectList(
    db.Riders
        .Select(r => new SelectListItem
            {
                Value = "test",
                Text = "test"
            })
        .ToArray());

If I hover over ViewBag.Raiders while debugging I can see some system fields and then items, which contains my SelectList (full of "test") and Results View, which contains SelectList with Text values of System.Web.Mvc.SelectListItem. What is the problem here? Where did that Results View come from and why is it populated with SelectItem class name?

My Razor looks like this:

 @Html.DropDownList("Riders", ViewBag.Raiders as SelectList)

I have tried using couple of different overloads of this DropDownList but to no success.

What am I doing wrong here? I thought accessing database with MVC is supposed to be easy. Its not intuitive for sure.

Alex
  • 715
  • 1
  • 8
  • 29
  • 1
    Using `new SelectList()` to create another identical `IEnumerable` is pointless. `ViewBag.Riders = db.Riders.Select(x => new SelectListItem{ Value = x.ID.ToString(), Text = x.FirstName });` –  Feb 25 '18 at 09:11
  • 1
    And you cannot use the same name for the property and the SelectList - refer [Can the ViewBag name be the same as the Model property name in a DropDownList?](https://stackoverflow.com/questions/37161202/can-the-viewbag-name-be-the-same-as-the-model-property-name-in-a-dropdownlist) –  Feb 25 '18 at 09:13
  • 1
    Or if you want to use `SelectList`, then its `ViewBag.Riders = new SelectList(db.Riders, "ID", "FirstName");` - note the 2nd parameter refer to the name of the property to use for the `value` attribute and the 3rd parameter refers to the named of the property to use for the option text –  Feb 25 '18 at 09:17
  • @StephenMuecke Thanks, it works now. However I had do use `db.Riders.AsEnumerable().Select`, otherwise it would throw error – Alex Feb 25 '18 at 09:39
  • Then you also have another problem with your code (something you did not show) because its not necessary –  Feb 25 '18 at 09:41
  • @StephenMuecke What Can i do wrong there? The Table definition looks like this: `public DbSet Riders { get; set; }`. – Alex Feb 26 '18 at 22:30
  • I can only assume you must be wrapping your code in a `using` statement so its disposed before the model is returned to the view –  Feb 26 '18 at 22:33
  • @StephenMuecke No such thing. I do not recollect the exact error but it was something like `LINQ to Entity. Cannot resolve Select`. I read about it in the internet and a proposed solution was to add `AsEnumerable` before `Select` query. – Alex Feb 27 '18 at 10:07

0 Answers0