I'm looking for a sound philosophy for bringing dynamic data into a view to populate a dropdownlist. Would it be a good idea to create a model object for dropdownlists and other "overhead" data or use a viewbag?
Thanks
I'm looking for a sound philosophy for bringing dynamic data into a view to populate a dropdownlist. Would it be a good idea to create a model object for dropdownlists and other "overhead" data or use a viewbag?
Thanks
Using the ViewBag (as some have suggested in other answers/comments) to get data from your controller to view is generally seen as a code lack.
Your ViewModel should ideally contain all of the data you need for your view. So use your controller to populate this data on a property of your ViewModel:
Here is a simple example of how to create a drop down list in ASP.NET MVC using Html.DropDownListFor using model. You can do it like this all inlined in your *.cshtml file like so:
which will create like this:
Refer to this answer for more information
Including the data in the View's Model or in the ViewBag are both good options, the best one depends entirely on your specific use case.
If this dropdown should be included on only one (or just a few) pages, it makes sense to be part of the ViewModel.
If every page should have the dropdown (if it's part of the menu, or footer for instance) you could create a BaseController that supplies ViewBag data for the dropdown, and let your other controllers inherit from that:
BaseController.cs
Any other controller
In my opinion View model should contain all the data that is needed for rendering the view and that is available on view creation.
Using ViewBag for me is like using
dynamic
type in code - it gives you some flexibility but comes with the price of possible errors, so i try to avoid as much as possibeExample for guidance:
I think the best way to achieve what you're after would be to use a
ViewModel
. You'd load the stuff you want to display in your View through this. So you'd create a dropdownlist with your accountlist which will be loaded in your controller. You'll also have your IEnumerable PErsoncontact in there which will also be loaded in your controller. Then your controller will pass the ViewModel to the View. You can use this as a guide.ViewModel:
Dropdownlist in Razor View :
Edit:- This is an example .Yes you can create a new class in same Model.
Dropdownlist in Razor View :