I want to know,What is a best way to create dropdownlists in MVC 4? With ViewBag or another approach?
What is the best way to create dropdownlists in MVC 4?
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.
Thank you,@Ant P.How can I get dataValueField in this example? –
Laaland
I want to write this new SelectList(Model.DisplayList, "TestplanId", "Name") –
Laaland
@ElvinArzumanoğlu I've added some information on how you can achieve this. –
Setaceous
It's very great example,,I think this approach(with last edit) is suitable for me. –
Laaland
It work fine. But now I have other problem, my dropdown doesn't select selecteditem –
Laaland
As 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. –
Setaceous
© 2022 - 2024 — McMap. All rights reserved.
ViewModel
. – Loudmouth