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

1

8

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

Laaland answered 20/4, 2013 at 8:11 Comment(4)
it's not View.Bag it is ViewBagFax
I'd recommend you pass them with your ViewModel.Loudmouth
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 viewBagLaaland
Bind dropdownlist in mvc4 razorSapodilla
S
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.

Setaceous answered 20/4, 2013 at 10:55 Comment(6)
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 selecteditemLaaland
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.