Ali Shahzad
Ali Shahzad

Reputation: 5332

Dropdownlist in Razor MVC 4

I want to add a DropDownList to my View with few static options without using ViewBag, and I want it to be bound with the Model. How can I do this?

Upvotes: 2

Views: 3692

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039498

Well, you start by writing the view model:

public class MyViewModel
{
    public string SelectedValue { get; set; }
    public IEnumerable<SelectListItem> Values { get; set; }
}

then a controller action that will populate this view model and pass it to the view:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel();

        // TODO: those values will probably be coming from a database or something
        model.Values = new[]
        {
            new SelectListItem { Value = "1", Text = "item 1" },
            new SelectListItem { Value = "2", Text = "item 2" },
            new SelectListItem { Value = "3", Text = "item 3" },
        };

        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        string selectedValue = model.SelectedValue;
        return Content("You selected: " + selectedValue);
    }
}

and finally a strongly typed view in which you could use the Html.DropDownListFor helper:

@model MyViewModel

@using (Html.BeginForm())
{
    @Html.DropDownListFor(x => x.SelectedValue, Model.Values)
    <button type="submit">OK</button>
}

The helper requires 2 parameters: the first is a lambda expression to a scalar property on your view model which will hold the selected value and the second is just an IEnumerable<SelectListItem> property which is holding all the available values that will be displayed in the dropdown.

Upvotes: 4

Related Questions