I have an ASP.NET MVC application with quite a few drop-down lists and multi-select lists. Essentially, a lot of lists of options.
My question is; is it better to pass these lists to the view as part of the Model, or as ViewData?
I am currently passing them as ViewData as I don't really need them on the model and they seem potentially bulky for passing around on the model (I get the selected item or items, which is really all I need). On the downside, ViewData needs casting on the View, which isn't as nice as the strongly typed model.
Is there a best practice here? Even suggestions of pros and cons for either of these would be appreciated.
All three objects are available as properties of both the view and controller. As a rule of thumb, you'll use the ViewData, ViewBag, and TempData objects for the purposes of transporting small amounts of data from and to specific locations (e.g., controller to view or between views).
ViewBag will be slower than ViewData; but probably not enough to warrant concern.
To summarize, ViewBag and ViewData are used to pass the data from Controller action to View and TempData is used to pass the data from action to another action or one Controller to another Controller.
ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using strings as keys. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0. ViewData requires typecasting for complex data type and check for null values to avoid error.
I recommend you to use ViewModels to pass that data. It's error prone to use ViewData with "magic strings" and I prefer to use intellisense instead of trying to remember that "magic strings". And you don't need to create that SelectLists in the controller. Just use some IEnumerable and use ToSelectList extension method from MvcContrib in the view.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With