What is the best ways to bind @Html.DropDownListFor in ASP.NET MVC5?

I want to bind @Html.DropDownListFor from Model data without using Viewbag and look at many different examples on the web. But most of them use Viewbag or an extension method and I want a better approach to solve this problem. I tried the the following methods but it does not seem to work:

@Html.DropDownListFor(m => m.LabId, new SelectList(Model.Lab, "Id", "Name"), 
    "---- Select----", new { @class = "selectpicker" } )

Is it possible to bind @Html.DropDownListFor directly from Model without using Viewbag or any extra method in the Controller in ASP.NET MVC5? Could you please give some examples to perform this best?


Solution 1:

The strongly typed view model approach which does not use dynamic stuff like ViewBag

You can add a new property to your view model for the SELECT options of type IEnumrable<SelectListItem>.

view model is a simple POCO class used to transfer data between view to action method and vice versa. They are specific to the views. Add properties only needed for the view.

public class CreateUserVm
{
   public IEnumrable<SelectListItem> Labs { set;get;}
   public int SelectedLabId { set;get;}
   //Add other properties as needed for the view
}

and in your GET action, create an object of this view model, load the Labs property and send that to the view.

public ActionResult Create()
{
  var vm= new CreateUserVm();
  // Hard coded for demo. You can replace with real data from db
  vm.Labs = new List<SelectListItem> {
     new SelectListItem { Value="1", Text="One" },
     new SelectListItem { Value ="2", Text="Two" }
  };
  return View(vm);
}

and in the view which is strongly typed to this view model, call the DropDownListFor helper method

@model CreateUserVm
@Html.DropDownListFor(f=>f.SelectedLabId, Model.Labs,"Select one")

Pre-selecting an option in the dropdown

If you like to pre select one option when razor renders the page, You can set the SelectedLabId property value of your view model to the value property value of of the Option item(SelectListItem).

public ActionResult Create()
{
  var vm= new CreateUserVm();
  // Hard coded for demo. You can replace with real data from db
  vm.Labs = new List<SelectListItem> {
     new SelectListItem { Value="1", Text="SugarLab" },
     new SelectListItem { Value ="2", Text="CandyLab" },
     new SelectListItem { Value ="3", Text="SodaLab" }
  };
  vm.SelectedLabId = 2; // Will set "CandyLab" option as selected
  return View(vm);
}

If you want to use real data, instead of the hard coded 2 items, you can do this

vm.Labs = dbContext.Labs.Select(x=>new SelectListItem { Value=x.Id.ToString(),
                                                        Text= x.Name }).ToList();

Assuming dbContext is your DbContext class object and it has a Labs property of type DbSet<Lab> where each Lab entity has an Id and Name property.