如何在MVC中填充DropDownList

时间:2016-05-12 18:26:55

标签: c# asp.net-mvc razor html.dropdownlistfor

刚刚开始使用MVC我已经尝试了很多教程/论坛帖子,但仍然无法填充我的DropDownList。我已经设法在视图中以ActionLinks的形式显示了pub名称(所以正确的数据保存在我的模型中吗?),但是DropDownLists没有成功。

我在第一次DropDownList尝试时收到的错误是:

“没有类型'IEnumerable'的ViewData项具有键'PubId'。”

型号:

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>

1 个答案:

答案 0 :(得分:0)

试试这个:

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