How can bind a Dropdownlist in MVC and use selected value?

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 🙂

Advertisement

4 thoughts on “How can bind a Dropdownlist in MVC and use selected value?”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s