I want to know,What is a best way to create dropdownlists in MVC 4? With ViewBag or another approach?
Asked
Active
Viewed 1.7k times
8
-
it's not View.Bag it is ViewBag – Dhaval Marthak Apr 20 '13 at 08:13
-
1I'd recommend you pass them with your `ViewModel`. – Artless Apr 20 '13 at 08:15
-
Hmm, I have many dropdownLists in View. I want to create them with ViewBag, but don't want to hurry, perhaps there are other ways that are gooder than viewBag – Elvin Mammadov Apr 20 '13 at 08:22
-
[Bind dropdownlist in mvc4 razor](http://lesson8.blogspot.com/2013/06/bind-dropdownlist-in-mvc4-razor.html) – Sender Oct 03 '13 at 16:03
1 Answers
10
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.

Ant P
- 24,820
- 5
- 68
- 105
-
1
-
I want to write this new SelectList(Model.DisplayList, "TestplanId", "Name") – Elvin Mammadov Apr 20 '13 at 11:24
-
1@ElvinArzumanoğlu I've added some information on how you can achieve this. – Ant P Apr 20 '13 at 11:26
-
It's very great example,,I think this approach(with last edit) is suitable for me. – Elvin Mammadov Apr 20 '13 at 11:28
-
It work fine. But now I have other problem, my dropdown doesn't select selecteditem – Elvin Mammadov Apr 20 '13 at 12:11
-
1As long as the expression in the first argument matches the View Model property that it should populate and you pass this model back into your controller POST method, it should work. If not, it sounds like a distinct issue for a separate question. – Ant P Apr 20 '13 at 14:49