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?
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.
and in your GET action, create an object of this view model, load the Labs property and send that to the view.
and in the view which is strongly typed to this view model, call the DropDownListFor helper method
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 thevalue
property value of of the Option item(SelectListItem).If you want to use real data, instead of the hard coded 2 items, you can do this
Assuming
dbContext
is your DbContext class object and it has aLabs
property of typeDbSet<Lab>
where each Lab entity has an Id and Name property.You are on a good track by having the list items in your model. I don't know how you have implemented that in your code.
The
Lab
property in your model class should be an IEnumerable, List or Collection of what you want. and then in your razor view, the looks fine.Perhaps what you're forgetting is to initialise the list from the action method in the controller before sending it to the view. E.g:
Above i assume the repository should be something that has access or means of getting the needed data, and also that the
Labs
property is defined asIEnumerable<Lab> Labs
in the ViewModel class.All should work. Perhaps you should be clear as to what error you're getting.