首页 > 解决方案 > EF Core .ToList() Query Returning "{Namespace.Models.Model}" Instead of Data

问题描述

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!

标签: c#asp.net-identityentity-framework-core

解决方案


这不是 Ef 问题。这是你在渲染 DropDownList 时的错。您必须将数据模式更改为正确的数据结构,例如 Dictionary 或 An Value-Text 类 (SelectList)。然后将其绑定到您的 DropDown。

这是您的问题的代码示例:

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

然后使用以下代码将其绑定到您的下拉列表:

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

推荐阅读