Can I create a picklist using the MVC3 helper

I am new to MVC3. I would like to create a select / drop down list that will allow me to choose between 2-3 things. I only want to be able to select one from the list. Is there an easy way to do this with an assistant.

Mary jean

Here is my idea.

The helper will select from choices: 1 answer 2 answers 3 answers 

and save the result in the task_type variable

+7
source share
1 answer

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.

+14
source

All Articles