Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to create dropdownlists in MVC 4?

I want to know,What is a best way to create dropdownlists in MVC 4? With ViewBag or another approach?

like image 871
Elvin Mammadov Avatar asked Apr 20 '13 08:04

Elvin Mammadov


People also ask

How can use static dropdown in MVC?

Binding MVC DropDownList with Static Values Just add an Html helper for DropDownList and provide a static list of SelectListItem. The values added as SelectListItem will be added and displayed in the DropDownList. In this way, you do not need to add anything to Controller Action.


1 Answers

I would argue that since the items are variable values within your view that they belong in the View Model. The View Model is not necessarily just for items coming back out of the View.

Model:

public class SomethingModel
{
    public IEnumerable<SelectListItem> DropDownItems { get; set; }
    public String MySelection { get; set; }

    public SomethingModel()
    {
        DropDownItems = new List<SelectListItem>();
    }
}

Controller:

public ActionResult DoSomething()
{
    var model = new SomethingModel();        
    model.DropDownItems.Add(new SelectListItem { Text = "MyText", Value = "1" });
    return View(model)
}

View:

@Html.DropDownListFor(m => m.MySelection, Model.DropDownItems)

Populate this in the controller or wherever else is appropriate for the scenario.

Alternatively, for more flexibility, switch public IEnumerable<SelectListItem> for public IEnumerable<MyCustomClass> and then do:

@Html.DropDownFor(m => m.MySelection,
    new SelectList(Model.DropDownItems, "KeyProperty", "ValueProperty")

In this case, you will also, of course, have to modify your controller action to populate model.DropDownItems with instances of MyCustomClass instead.

like image 83
Ant P Avatar answered Sep 22 '22 15:09

Ant P