Bind (Populate) DropDownListFor using ViewBag in ASP.Net MVC

leila398
 
on Nov 16, 2021 02:42 AM
Sample_370035.zip
584 Views

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

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Nov 16, 2021 03:13 AM

Hi leila398,

Check this example. Now please take its reference and correct your code.

Database

For this example I have used of Northwind database that you can download using the link given below.

Download Northwind Database

Model

public class staff
{
    public int Id { get; set; }
    public string staffname { get; set; }
}

Namespaces

using System.Configuration;
using System.Data.SqlClient;

Controller

public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        SelectList list = new SelectList(GetStaffList(), "Id", "staffname");
        ViewBag.StaffList = list;
        return View();
    }

    public List<staff> GetStaffList()
    {
        string _Connection = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection conn = new SqlConnection(_Connection))
        {
            var command = new SqlCommand("SELECT EmployeeID,FirstName FROM Employees", conn);
            conn.Open();
            SqlDataReader reader = command.ExecuteReader();
            List<staff> staffTbl = new List<staff>();
            while (reader.Read())
            {
                staffTbl.Add(new staff
                {
                    Id = Convert.ToInt32(reader["EmployeeID"]),
                    staffname = reader["FirstName"].ToString()
                });
            }
            conn.Close();

            return staffTbl;
        }
    }
}

View

@model ViewBag_DropDownList_MVC.Models.staff
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    @Html.LabelFor(model => model.staffname)
    @Html.DropDownListFor(model => model.staffname, (IEnumerable<SelectListItem>)ViewBag.StaffList, "Select")
</body>
</html>

Screenshot