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
Select Add >> New item. After that, select the ADO.NET Entity Data Model and click on "Add" button. Now, Entity Data Model Wizard is open. Select -> "The Generate from database" option and click Next.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With