C# ASP.NET MVC Forms Creating a Basic Form Using Model Binding to Capture POST Data

Johan Rönkkö
Johan Rönkkö
28,054 Points

How would you go about binding a select-box?

It's options all have their own value attribute. Would you go <option value="@ViewBag.Example>Example</option> on each and every option?

2 Answers

Steven Parker
Steven Parker
204,000 Points

The option values don't change, so you don't need to set them from the ViewBag.

What's significant in the select is which option has the selected attribute. So you might do this:

<option value="1" @if (ViewBag.Myselect == "1") { Html.Raw("selected") }>Choice 1</option>
<option value="2" @if (ViewBag.Myselect == "2") { Html.Raw("selected") }>Choice 2</option>
<option value="3" @if (ViewBag.Myselect == "3") { Html.Raw("selected") }>Choice 3</option>
... etc.
James Churchill
STAFF
James Churchill
Treehouse Teacher

The first two videos of stage 3 show you how to use MVC's Html.DropDownListFor HTML helper method to work with HTML select lists. Until you get there, Steven's solution is a great stop gap.