How to create static combo box values ​​in the MVC template

advertisements

How can I prepare a model for Dropdownlist static values (not retrieved from database) like enum or list in MVC Model so that it could be used many times in a project? I would appreciate if you can give a good article? Thanks.


As always you could start with a view model:

public class MyViewModel
{
    public string SelectedValue { get; set; }
    public IEnumerable<SelectListItem> Values
    {
        get
        {
            return new[]
            {
                new SelectListItem { Value = "1", Text = "Item 1" },
                new SelectListItem { Value = "2", Text = "Item 2" },
                new SelectListItem { Value = "3", Text = "Item 3" },
            };
        }
    }
}

then a controller:

public ActionResult Index()
{
    var model = new MyViewModel();
    return View(model);
}

and finally a view:

@model MyViewModel
@Html.DropDownListFor(x => x.SelectedValue, Model.Values)

For enums you could use some of the many posts out there illustrating custom helpers. Here's one blog post illustrating such helper: http://blogs.msdn.com/b/stuartleeks/archive/2010/05/21/asp-net-mvc-creating-a-dropdownlist-helper-for-enums.aspx