0

This is my first attempt to populate a dropdown using a List<> collection. I am not quite sure I am doing this right, so any instruction would be great. I don't think I am getting the right information to the list in the view?

My model looks like:

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;
            }

        }

My view contains:

        @Html.Label("Product Type: *");
        @Html.DropDownListFor(m => m.LOBTypes, new SelectList(Model.LOBTypes, "NAME"));
Kevin Schultz
  • 886
  • 3
  • 20
  • 42
  • I did and most referred to IList or IEnumerable. Interestingly enough a search with my exact title reveals 57 questions and mine is the only one with that title. Thanks for the help. – Kevin Schultz Apr 27 '15 at 18:28

1 Answers1

1

You have the arguments to DropDownListFor the wrong-way-around.

The first argument should be the ViewModel property that stores the selected value. The second argument should be a list of SelectListItem which will appear as options to the user. This should be passed as a property of ViewData rather than ViewModel if it's coming from a database.

Also, you're not correctly disposing of your database objects.

Something like this:

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"] );
Dai
  • 141,631
  • 28
  • 261
  • 374