We help IT Professionals succeed at work.

MVC Razor DropDownList not populating value, system.data.datarow instead

Eric Robuck
Eric Robuck asked
on
I am diving into MVC and hit a snag.

In my home controller I am populating a ViewBag. Then I am trying to put that into a drop down list

Home controller:

 
string _connectionString = WebConfigurationManager.ConnectionStrings["xxxxxxx"].ToString();

            using (SqlConnection con = new SqlConnection(_connectionString))
            {
                //
                // Open the SqlConnection.
                //
                con.Open();
                //
                // The following code uses an SqlCommand based on the SqlConnection.
                //

            
                SqlDataAdapter _da = new SqlDataAdapter("Select Name from AspNetRoles", con);
                DataTable _dt = new DataTable();


                _da.Fill(_dt);
                
                ViewBag.RoleList = new SelectList(_dt.AsEnumerable());

                
                con.Close();
                
            }

Open in new window


Index.html :
 
@Html.DropDownList("Name", (IEnumerable<SelectListItem>)ViewBag.RoleList, "Select an application", "Name")

Open in new window



My dropdown populates the correct number of rows, however the proper text does not come up=> system.data.datarow is there 6 times

I am sure I am not converting something....can you help me with this easy newbie question?
Comment
Watch Question

Developer
CERTIFIED EXPERT
Distinguished Expert 2019
Commented:
Try this instead:
ViewBag.RoleList = new SelectList(_dt.Rows.Cast<DataRow>().Select(r => r["Name"]));

Open in new window

-saige-

Author

Commented:
That worked!!  Thank you