我对这个 MVC 框架非常陌生,并试图找出一个非常简单的操作 - 从数据库中填充下拉列表。我设法从数据库中获取了一个值列表,但由于某种原因无法获得一个不同的列表。这是我的示例代码
public class HomeController : Controller
{
private PlanContext _context = new PlanContext();
public ActionResult Index()
{
var query = _context.Categories.Select(m => new { m.ID }).Distinct();
ViewBag.CategoryID = new SelectList(query.AsEnumerable(), "ID", "ID");
return View();
}
}
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<p>
Select a Category:<%= Html.DropDownList("ID", (SelectList) ViewBag.CategoryID, "---Select One---") %>
</p>
</asp:Content>
public class PlanContext : DbContext
{
public DbSet<Category> Categories { get; set; }
}
[Table("vCategory")]
public class Category : IEquatable<Category>
{
[Column("CategoryID")]
public int ID { get; set; }
public bool Equals(Category other)
{
//Check whether the compared object is null.
if (Object.ReferenceEquals(other, null)) return false;
//Check whether the compared object references the same data.
if (Object.ReferenceEquals(this, other)) return true;
return ID == other.ID;
}
public override int GetHashCode()
{
return ID.GetHashCode();
}
}
我的下拉菜单总是有多个具有相同 ID 值的项目。该表确实有重复的值,但我试图用 Distinct 填充 DDL。
谢谢你的帮助。
贾维德