Bind DropDownList in ASP.Net MVC 4 or 5 Using C# Using Entity Framework

    Create MVC4 or application,then create model class
    In our model file we will add the below code. 
   
    public class TeacherlistModel
    {
        public System.Web.Mvc.SelectList SubjectListModel { getset; }
    }
    public class SubjectList
    {
        public int SubjectId { getset; }
        public string SubjectName { getset; }
}

In your controller add the below code to bind the dropdownlist.

     public ActionResult Create()
        {
           
            List<SubjectList> objSubjectList = new List<SubjectList>();
            objSubjectList = (from val in objEntity.tblSubjects
                              select new SubjectList
                              {
                                  SubjectId = val.id,
                                  SubjectName = val.Subject_Name
                              }).ToList();

            SubjectList objSubjectListdtl = new SubjectList();
            objSubjectListdtl.SubjectName = "Select";
            objSubjectListdtl.SubjectId = 0;
            objSubjectList.Insert(0, objSubjectListdtl);
            SelectList objmodeldata = new SelectList(objSubjectList, "SubjectId""SubjectName", 0);
            /*Assign value to model*/
           
            return View(objmodeldata);
        }

Now  create View for the model. In this view we will add all the HTML tags.
   
@Html.DropDownList("ddlSubject", Model.SubjectListModel, new { @style = "width:200px;" })





Now learn how we can retrieve the selected value at controller end. For this you need  to create post method in the controller. 
Now add the below post method in your controller.
       [HttpPost]
       public ActionResult Create(int ddlSubject)
       {
            return RedirectToAction("/Index");
   }
              

Comments

Popular posts from this blog

Validate Mobile Number with 10 Digits in ASP.Net