【问题标题】:Populate dropdown from List<> collection [duplicate]从 List<> 集合中填充下拉列表 [重复]
【发布时间】:2015-04-27 17:43:11
【问题描述】:

这是我第一次尝试使用 List 集合填充下拉列表。我不太确定我做对了,所以任何指示都会很棒。我认为我没有在视图中的列表中获得正确的信息?

我的模型看起来像:

public List<LOB> LOBTypes
        {
            get
            {
                try
                {
                    using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MNB_connectionstring"].ConnectionString))
                    {
                        SqlCommand cmd = new SqlCommand("SELECT CODE, NAME FROM BOA_LOB_Details ORDER BY NAME", con);
                        cmd.CommandType = CommandType.Text;

                        SqlDataReader dr = cmd.ExecuteReader();

                        if (dr.HasRows)
                        {
                            while (dr.Read())
                            {
                                _LOBTypes.Add(new LOB { Code = dr["CODE"].ToString(), Name = dr["NAME"].ToString() });
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    ExceptionUtility.LogException(ex, "GetLOBTypes()");
                }
                return _LOBTypes;
            }

        }

我的观点包含:

        @Html.Label("Product Type: *");
        @Html.DropDownListFor(m => m.LOBTypes, new SelectList(Model.LOBTypes, "NAME"));

【问题讨论】:

  • 我做过并且最常提到 IList 或 IEnumerable。有趣的是,使用我的确切标题进行搜索会发现 57 个问题,而我的是唯一一个具有该标题的问题。感谢您的帮助。

标签: c# asp.net-mvc razor


【解决方案1】:

你对 DropDownListFor 的论点是错误的。

第一个参数应该是存储所选值的 ViewModel 属性。 第二个参数应该是SelectListItem 的列表,它将作为选项显示给用户。如果它来自数据库,则应将其作为 ViewData 的属性而不是 ViewModel 传递。

另外,您没有正确处理数据库对象。

类似这样的:

List<SelectListItem> items = new List<SelectListItem>();
while( dr.Read() ) {

    SelectListItem li = new SelectListItem() {
        Text = dr.GetString("NAME"),
        Value = dr.GetString("CODE")
    };
    items.Add( li );
}
ViewData["ListItems"] = items;

////

@Html.DropDownListFor( m => m.LOBTypes, this.ViewData["ListItems"] );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 2021-04-04
    • 1970-01-01
    相关资源
    最近更新 更多