Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create a select list with a MVC3 helper

Tags:

asp.net-mvc

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

like image 651
MaryJean Avatar asked Jun 07 '11 07:06

MaryJean


People also ask

How do I add a dropdown in Entity Framework?

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.


1 Answers

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.

like image 191
Darin Dimitrov Avatar answered Oct 03 '22 09:10

Darin Dimitrov