Hello I am new to MVC and webdevelopment and I am stuck with Viewbag. I am trying to populate dropdownlist with names from a staff table.
Here is a method that is meant to get the names:
public List<string> GetStaffList()
{
using (SqlConnection conn = new SqlConnection(_Connection))
{
var command = new SqlCommand(GetReadQuery(), conn);
conn.Open();
var result = String.Empty;
var reader = command.ExecuteReader();
staff staffTbl = new staff();
if (reader.HasRows)
{
while (reader.Read())
{
reader.Read();
DropDownList.Add(reader["name"].ToString());
}
}
conn.Close();
return DropDownList;
}
}
When I step through it looks like DropDownList stores all the items as I can see the count and names. But it eventually throws an error saying Invalid attempt to read when no data is present.
Here is the controller calling this method:
public ActionResult DropdownList()
{
var dropdowngenerator = new DropdownGenerator(connString);
var getList = dropdowngenerator.GetStaffList().ToList();
SelectList list = new SelectList(getList);
ViewBag.StaffList = list;
return View();
}
And then here is the View with the dropdownlist:
<div class="form-group">
@Html.LabelFor(model => model.staffname, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.staffname, (SelectList)ViewBag.StaffL)
@Html.ValidationMessageFor(model => model.staffname, "", new { @class = "text-danger" })
</div>
</div>
Please help I would be very grateful