Populate DropDownList with Model class using Entity Framework in ASP.Net MVC

akhter
 
on Nov 09, 2021 02:04 PM
516 Views

Populate Dropdownlist in MVC using entity Frame Work

i am trying to populate dropdownlist using entity Frame Work.

i have one model in which i bind two table.  tbl_Student and tbl_class

code of controller 

namespace WebApplication6.Controllers
{
    public class SaveDataController : Controller
    {
        // GET: SaveData

        public ActionResult Index()
        {
            ViewBag.saveresult = "";
            return View();
        }

        [HttpPost]
        public ActionResult Index(tbl_Student student)
        {
            using (SchoolDataEntities entities = new SchoolDataEntities())
            {
                entities.tbl_Student.Add(student);
                entities.SaveChanges();
                ViewBag.saveresult = "Data Save";
                ModelState.Clear();
            }
            return View(new tbl_Student());
        }
        public ActionResult Indexd()
        {
            List<SelectListItem> ClassList = GetClasss();
            return View(ClassList);
        }
        [HttpPost]
        public ActionResult Indexd(string ddlclass)
        {
            List<SelectListItem> ClassList = GetClasss();
            if (!string.IsNullOrEmpty(ddlclass))
            {
                SelectListItem selectedItem = ClassList.Find(p => p.Value == ddlclass);
                ViewBag.Message = "Name: " + selectedItem.Text;
                ViewBag.Message += "\\nID: " + selectedItem.Value;
            }
            return View(ClassList);
        }

        private static List<SelectListItem> GetClasss()
        {
            SchoolDataEntities entities = new SchoolDataEntities();
            List<SelectListItem> classList = (from p in entities.tbl_Class.AsEnumerable()
                                              select new SelectListItem
                                              {
                                                  Text = p.Class_Name,
                                                  Value = p.Class_ID.ToString()
                                              }).ToList();


            //Add Default Item at First Position.
            classList.Insert(0, new SelectListItem { Text = "--Select Class--", Value = "" });
            return classList;
        }
    }
}

View

@model WebApplication6.Models.tbl_Student

@{
    Layout = null;
}
<html>
<head>

    <meta name="viewport" content="width=device-width" />
    <title></title>
</head>
<body>
    <h1>
        Study
    </h1>
    <h4>
        Insert Data into Database   AKhter
    </h4>
    <div>
        @using (Html.BeginForm("Index", "SaveData", FormMethod.Post))
        {
            <table border="1" bgcolor="yellow" width="400px" height="250px">
                <tr>
                    <td>Roll Number</td>
                    <td>  @Html.TextBoxFor(m => m.std_id, "{0:#.#}")</td>
                </tr>
                <tr>
                    <td>
                        Student Name
                    </td>
                    <td>  @Html.TextBoxFor(m => m.std_Name)</td>
                </tr>
                <tr>
                    <td>
                        Class
                    </td>
                    <td>
                        @Html.DropDownList("ddlclass", Model)
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <input type="submit" value="Submit" />
                    </td>
                </tr>
                <tr></tr>
            </table>
        }
    </div>
    <b>@ViewBag.saveresult</b>
</body>
</html>

but dropdownlist is not populating 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Nov 10, 2021 07:20 AM

Hi akhter,

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 tbl_Student
{
    public string std_id { get; set; }
    public string std_Name { get; set; }
    public List<SelectListItem> ClassList { get; set; }
}

Controller

public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        tbl_Student student = new tbl_Student();
        student.ClassList = GetClasss();
        ViewBag.saveresult = "";
        return View(student);
    }

    [HttpPost]
    public ActionResult Index(tbl_Student student)
    {
        using (NorthwindEntities entities = new NorthwindEntities())
        {
            Customer s = new Customer();
            s.CustomerID = student.std_id;
            s.ContactName = student.std_Name;
            entities.Customers.Add(s);
            entities.SaveChanges();
            ViewBag.saveresult = "Data Save";
            ModelState.Clear();
        }

        return View(new tbl_Student() { ClassList = GetClasss() });
    }

    private static List<SelectListItem> GetClasss()
    {
        NorthwindEntities entities = new NorthwindEntities();
        List<SelectListItem> classList = (from p in entities.Customers
                                            select new SelectListItem
                                            {
                                                Text = p.ContactName,
                                                Value = p.CustomerID.ToString()
                                            }).ToList();

        //Add Default Item at First Position.
        classList.Insert(0, new SelectListItem { Text = "--Select Class--", Value = "" });
        return classList;
    }
}

View

@model DropDownList_MVC.Models.tbl_Student

@{
    Layout = null;
}
<html>
<head>

    <meta name="viewport" content="width=device-width" />
    <title></title>
    <script>

    </script>
</head>
<body>
    <h1>
        Study
    </h1>
    <h4>
        Insert Data into Database   AKhter
    </h4>
    <div>
        @using (Html.BeginForm("Index", "Home", FormMethod.Post))
        {
            <table border="1" bgcolor="yellow" width="400px" height="250px">
                <tr>
                    <td>Roll Number</td>
                    <td>  @Html.TextBoxFor(m => m.std_id, "{0:#.#}")</td>
                </tr>
                <tr>
                    <td>
                        Student Name
                    </td>
                    <td>  @Html.TextBoxFor(m => m.std_Name)</td>
                </tr>
                <tr>
                    <td>
                        Class
                    </td>
                    <td>
                        @Html.DropDownList("ddlclass", Model.ClassList)
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <input type="submit" value="Submit" />
                    </td>
                </tr>
                <tr></tr>
            </table>
        }
    </div>
    <b>@ViewBag.saveresult</b>
</body>
</html>