You can use the DropDownListFor helper. I would start by defining a view model:
public class AnswersViewModel { public string SelectedAnswer { get; set; } public IEnumerable<SelectListItem> Answers { get { return new[] { new SelectListItem { Value = "1", Text = "1 answer" }, new SelectListItem { Value = "2", Text = "2 answers" }, new SelectListItem { Value = "3", Text = "3 answers" }, }; } } }
then the controller:
public class HomeController : Controller { public ActionResult Index() { var model = new AnswersViewModel(); return View(model); } [HttpPost] public ActionResult Index(AnswersViewModel model) { return View(model); } }
and finally, a strongly typed view:
@model AnswersViewModel @using (Html.BeginForm()) { @Html.DropDownListFor( x => x.SelectedAnswer, new SelectList(Model.Answers, "Value", "Text") ) <input type="submit" value="OK" /> }
Now, when the user submits the form, the Index POST action will be called, and the SelectedAnswer property of the view model will be automatically populated with the user's choice from the drop-down list.
Darin Dimitrov
source share