2016-05-12 73 views
-1

在剛開始使用MVC時,我嘗試了大量的教程/論壇帖子,但仍然無法讓我的DropDownList被填充。我已經設法在視圖中以ActionLinks的形式顯示酒吧名稱(所以正確的數據被保存在我的模型右邊?),但DropDownLists沒有成功。如何在MVC中填充DropDownList

我的第一個DropDownList嘗試收到錯誤讀取:

「有型‘的IEnumerable’具有關鍵‘pubId’的不ViewData的項目」

型號:

namespace WineMenu.Models 
{ 
    public class PubListModel 
    {  
     public List<Pub> _pl = new List<Pub>(); 

     public List<Pub> PubList 
     { 
      get 
      { 
       if (_pl.Count == 0) 
       { 
        _pl = GetPubs(); 
       } 

       return _pl; 
      } 
     } 

    public List<Pub> GetPubs() 
    { 
      List<Pub> _pl = new List<Pub>(); 

      SqlConnection con = new SqlConnection(); 
      con.ConnectionString = "Data Source=XXX\\SQLEXPRESS;Initial Catalog=DB_WineMenu;Integrated Security=True"; 
      con.Open(); 

      using (con) 
      { 
       SqlCommand cmd = new SqlCommand("SELECT * FROM Pub", con); 
       SqlDataReader rd = cmd.ExecuteReader(); 

       while (rd.Read()) 
       { 
        Pub p = new Pub(); 

        p.PubId = Convert.ToInt32(rd.GetInt32(0)); 
        p.PubName = Convert.ToString(rd.GetSqlValue(1)); 

        _pl.Add(p); 
       } 
      } 
      return _pl; 
    } 
    } 

    public class Pub 
    { 
     public int PubId { get; set; } 
     public string PubName { get; set; } 
    } 

控制器:

public ActionResult GetPubs() 
     { 
      PubListModel p = new PubListModel(); 

      return View("GetPubs", p); 
     } 

查看:

@model WineMenu.Models.PubListModel 

@{ 
    ViewBag.Title = "GetPubs"; 
} 

<h2>GetPubs</h2> 

@*<h2>Pubs- Last Updated: @Model.PubName</h2>*@ 

<h4>@ViewBag.Message</h4> 
<ul> 
    @foreach (var pub in Model.PubList) 
    { 
     <li>@Html.ActionLink(pub.PubName, "Browse", new { pub = pub.PubName })</li> 

     @Html.DropDownList("PubId", pub.PubName) 
     @* @Html.DropDownListFor(p => p.PubList, Model.PubList)*@ 
    } 

</ul> 
+0

好耶您正嘗試創建一個針對Pub類的下拉列表。這正是我想要的,除了它的迴應。你在這裏做什麼? – asawyer

+0

感謝您的回覆。我試圖用我的數據庫中的所有酒吧填充DropDownList。該模型具有一個list屬性,通過GetPubs()方法獲取數據庫中的所有pubs。 Controller實例化Model,並將其傳遞給GetPubs視圖。我可以看到該模型已通過調試器填充。希望這有助於? – Nick

+0

您的模型甚至沒有要綁定的屬性(即對於選定的「Pub」)。你的模型需要2個屬性:'int SelectedPub'和'IEnumerable 'PubList',並且在視圖中它的'@ Html.DropDownListFor(m => m.SelectedPub,Model.PubList)'。建議你閱讀[這個問題/答案](http://stackoverflow.com/questions/34366305/the-viewdata-item-that-has-the-key-xxx-is-of-type-system-int32-but-必須是o)瞭解基礎知識。 –

回答

0

試試這個:

@Html.DropDownListFor(m => m.PubId, new SelectList(Model.PubListModel , "PubId", "PubName "), "--Select--", new { @class = "form-control" })