EP2012
EP2012

Reputation: 341

Html.DropDownList populating

I have a drop down in my MVC project.

@Html.DropDownList("Chart Type", new List<SelectListItem>
    {
        new SelectListItem{ Text="Horizontal", Value = "Horizontal" }, 
        new SelectListItem{ Text="Vertical", Value = "Vertical" },
        new SelectListItem{ Text="Pie", Value = "Pie" }
    }, 
    new { @class = "chzn-select", @multiple ="true", @style="width:350px;"} )

This puts hard coded values in the list. If I want to get the values from a database, what is the best approach?

Can I have the Html.DropDownList reference a sql query or SP for populating the list?

Upvotes: 0

Views: 2515

Answers (2)

Forty-Two
Forty-Two

Reputation: 7605

Create a view model with (at least) two properties:

public class ViewModel()
{
   public List<SelectListItem> Items { get; set; }
   public string SelectedItem { get; set; }
}

In your controller, make the call to your data source and populate the Items property of the view model and pass it to the view.

public ActionResult Index()
{
   var viewModel = new ViewModel();
   viewModel.Items = database.GetChartTypes();//or however you're accessing your data
   return View(viewModel);
}

Then strongly type your view and use the DropDownListFor helper

@model MyProject.ViewModel
...
@Html.DropDownListFor(m => m.SelectedItem, 
                      Items,
                      "--Select a Chart Type--",
                      new { @class = "chzn-select", 
                            @multiple ="true", 
                            @style="width:350px;"
                          });

Upvotes: 5

Andy T
Andy T

Reputation: 9901

You do not want the UI making calls to your data layer.

What you would want is the controller either calling a "service" that then calls the repository, or the controller calling the repository to get the list.

Once it has the list, it will pass that to the view using a ViewModel or the ViewBag.

Upvotes: 2

Related Questions