我對這個MVC框架非常陌生,並試圖找出一個非常簡單的操作 - 從數據庫填充下拉列表。我設法從數據庫中獲取值的列表,但由於某種原因無法獲得明確的列表。這裏是我的示例代碼ASP.Net 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值相同的項目。該表具有重複的值,但我試圖用不同的DDL填充DDL。
感謝您的幫助。
Javid
謝謝。在我的情況下,我試圖查詢的表有兩個列類別和產品。我需要獲得不同類別的清單。在這種情況下,如何定義映射到具有多列的表的實體,但實體只有一列作爲特權? – user320587
@ user320587:這是不可能的。數據庫表中的主鍵是什麼? 'ProductId'或'CategoryId' +'ProductId'(複合鍵)?您需要將此數據庫鍵映射到模型類中的鍵。 – Slauma
謝謝。 DB中的視圖沒有任何PK,因爲我的大部分工作都是隻讀的。在我的EF中,我將兩列標記爲Key來創建組合,並且它似乎工作正常。非常感謝你的幫助。 – user320587