EF Core .ToList() Query Returning "{Namespace.Models.Model}" Instead of Data

asp.net-identity c# entity-framework-core

Question

I have a model called Situation and I'm simply getting all of them so I can list them in a dropdown box in a view. Here's my query:

var situations = _context.Situations.ToList();

Dropdown box:

@Html.DropDownList("SituationID", null, "Pick One: ", new { @class = "form-control" })

The weird part is that each of the elements in the returned set are my Namespace.Models.Situation instead of the values at the top level.

My other query to return users (public class ApplicationUser : IdentityUser) returns their email addresses for [0], 1... then the properties below them. Here are screenshots at a break point:

enter image description here

enter image description here

enter image description here

Other than the fact I still have very little understanding about how to use the @Html.DropDownList HtmlHelper (more on that in other questions), I can't figure out what's different between the two. There are no errors clearly, but I have no idea where to go from here. Thanks!

1
0
12/30/2018 7:10:32 AM

Accepted Answer

I think you need to transform your list of Situation items into a list of SelectListItem. It should be something like:

ViewBag.Situations = _context.Situations
    .Select(situation => new SelectListItem { Text = situation.XXX, Value = situation.YYY })
    .ToList();

And then in your view:

@Html.DropDownList("SituationID", ViewBag.Situations, "Pick One: ", new { @class = "form-control" })

Where XXX and YYY are the properties you want to use as the display text of the item and the ID of the item (respectively).

You can also take a look at Using the DropDownList Helper with ASP.NET MVC for a complete example.

Hope it helps!

2
12/30/2018 7:46:54 AM

Popular Answer

this is not Ef Problem. this is your fault in rendering DropDownList. You must change your data schema to a proper data structure such as Dictionary or An Value-Text class (SelectList). and then Bind it to your DropDown.

this is code example for your problem:

ViewBag.SituationList = _context.Situations.Select( x=> new SelectListItem{Value= x.Id, , Text= x.SituationName}).ToList();

and then Bind it to your Dropdown using this code:

@Html.DropDownListFor(model => model.label, (SelectList)ViewBag.SituationList)


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow