Search code examples
c#asp.netasp.net-mvcmodelbinder

ASP.NET MVC - Modelbinding with Dropdownlist


Is it possible to have a single view model with a list that is used for a dropdownlist and also get the selected value of the dropdownlist from the view model when I post a form?

If so, how can I do this?


Solution

  • Sure, as always start by defining your view model:

    public class MyViewModel
    {
        public int? SelectedItemValue { get; set; }
        public IEnumerable<Item> Items { get; set; }
    }
    
    public class Item
    {
        public int? Value { get; set; }
        public string Text { get; set; }
    }
    

    then the controller:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var model = new MyViewModel
            {
                // TODO: Fill the view model with data from
                // a repository
                Items = Enumerable
                    .Range(1, 5)
                    .Select(i => new Item 
                    { 
                        Value = i, 
                        Text = "item " + i 
                    })
            };
            return View(model);
        }
    
        [HttpPost]
        public ActionResult Index(MyViewModel model)
        {
            // TODO: based on the value of model.SelectedItemValue 
            // you could perform some action here
            return RedirectToAction("Index");
        }
    }
    

    and finally the strongly typed view:

    <% using (Html.BeginForm()) { %>
        <%= Html.DropDownListFor(
            x => x.SelectedItemValue, 
            new SelectList(Model.Items, "Value", "Text")
        ) %>
        <input type="submit" value="OK" />
    <% } %>