Having just started out on MVC I've tried numerous tutorials/forum posts but still can't get my DropDownList to be populated. I've managed to display the pub names in the form of ActionLinks in the view (so the correct data is being held in my Model right?), but have been unsuccessful with DropDownLists.
The error I recieve on the first DropDownList attempt reads:
"There is no ViewData item of type 'IEnumerable' that has the key 'PubId'."
Model:
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; }
}
Controller:
public ActionResult GetPubs()
{
PubListModel p = new PubListModel();
return View("GetPubs", p);
}
View:
@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>