DropDown Model

The drop down model is used when you would like to specify the value and the SelectList on your view model.

The DropDown model only consists of two properties: an object Value and an IEnumerable<SelectListItem> Options:

namespace MvcTemplates.Model
{
    public class DropDown
    {
        public object Value { get; set; }
        public IEnumerable<SelectListItem> Options { get; set; }
    }
}

dropdown model use case
public class ChooseCityViewModel
{
    [Required]
    public DropDown City { get; set; }
}

[HttpGet]
public ActionResult ChooseCity( int userId )
{
    var user = UserRepository.FindById( userId );
    var cities = CityRepository.FindAll();

    var citiesDropDown = new DropDown
                        {
                            Value = user.City.Id,
                            Options = new SelectList( cities, "Id", "Name" )
                        };
    var viewModel = new ChooseCityViewModel
                        {
                            City = citiesDropDown
                        };
    return View( viewModel );
}

[HttpPost]
public ActionResult ChooseCity( int userId, ChooseCityViewModel model )
{
    var selectedCity = model.City.Value;
    var user = UserRepository.FindById( userId );
    user.City = CityRepository.FindById( selectedCity );
    UserRepository.Update( user );
    return RedirectToAction( "ChooseCity", new {userId} );
}

the rendered drop down can be completely customized by using the HtmlAttributes attribute!

If you prefer to use view data to hold your options, I suggest you look at the DropDownAttribute class.

Last edited Feb 22, 2011 at 2:55 AM by brk6004, version 6

Comments

No comments yet.