Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Model vs ViewData For Select Lists

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.

like image 691
Fenton Avatar asked Feb 26 '10 15:02

Fenton


People also ask

When should we use ViewData?

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).

Is ViewData faster than ViewBag in MVC?

ViewBag will be slower than ViewData; but probably not enough to warrant concern.

What is difference between ViewData and TempData in MVC?

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.

What is the difference between ViewBag and ViewData in ASP NET MVC?

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.


1 Answers

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.

like image 61
zihotki Avatar answered Sep 28 '22 21:09

zihotki