Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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
231,268 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.