I want to know,What is a best way to create dropdownlists in MVC 4? With ViewBag or another approach?
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.