Can I create a select list with a MVC3 helper
I'm new to MVC3. I would like to create a select list / dropdown that will allow me to select between 2-3 things. I only want to be able to select the one from a list. Is there an easy way to do this with a helper.
Mary Jean
Here's my idea. 开发者_开发知识库
The helper will select from choices:
1 answer
2 answers
3 answers
and store the result in task_type variable
You could 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 a 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 invoked and the SelectedAnswer
property of the view model will be automatically populated with the user selection from the dropdown.
精彩评论