If you have been a ASP.Net programmer and now you decided to move to MVC this post can help you to find out how populate a Dropdownlist and how use selected value when the form is posted to the controller.
What is scenario?
I have this table in the database, as you see here, this table contains student’s information, I need a Dropdownlist in the form for list of available programs that user can select for each students.
Id | int |
Name | nvarchar(50) |
Family | nvarchar(50) |
Tel | nvarchar(50) |
Address | nvarchar(50) |
ProgramId | int |
In this function I created a list that contains program information (value, text), then I wanted to assign it to the DropDownlist:
public ActionResult Create() { IEnumerable<SelectListItem> ProgramList= new[] { new SelectListItem { Value = "1", Text = "bachelor" }, new SelectListItem { Value = "2", Text = "Master" }, new SelectListItem { Value = "3", Text = "PHD" }, }; ViewBag.List = ProgramList; return View(); }
After that you need to make a view base on Student class, because we need to use ProgramId to post back a selected program’s Id and other student information to the controller that want to save data.
Here I just show you how to create a DropDownlist and I ignore other student’s fields:
<form method="post" action="students/create"> @Html.DropDownListFor(model => model.ProgramId, new SelectList(ViewBag.List, "Value", "Text")) <input type="submit" /> </form>
I am sure that this post it is not clear for those programmer that are new in MVC , therefore if you need more help , just leave comment here then I will help you to improve your knowledge in MVC and also I can help you to find good reference to learn MVC 🙂
Very shortly this web page will be famous amid all
blog viewers, due to it’s pleasant articles
its not working…
up to now i didn’t know how can i pass the drop down list value from view to controller
how can i fill country in dropdown using selected value from database for curresponding id