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 { get; set; }
}
public class SubjectList
{
public int SubjectId { get; set; }
public string SubjectName { get; set; }
}
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 a 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
Post a Comment