2016-05-12 100 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" })