Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to expose multiple objects to a view in ASP.NET MVC?

Tags:

asp.net-mvc

I'm kind of new to ASP.NET MVC and to the MVC pattern in general but I'm really digging the concept and the rapidity with which I can compose an app. One thing that I'm struggling with is how to expose more than one object to a view. I use a lot of strongly typed views, which works well but what if my view relies on more than one object? Right now I'm doing something pretty hacky and passing a Dictionary to the view and then just keying the different objects. Is there a better pattern for this?

like image 434
JC Grubbs Avatar asked Dec 04 '22 16:12

JC Grubbs


1 Answers

You have two primary options and either could work well depending on your application.

1) Just put objects into the ViewData collecion. This works well if you have lots of different controllers that pass different data to different views. It also depends on how much boxing/unboxing you want from object as you cast objects to their correct types. This option is more flexible, but less type-safe and possibly more fragile.

2) Create strongly-typed objects that contain other strongly-typed objects useful to a set of views. This works well if you tend to pass the same data to most of your views and you have fewer controllers.

You could also consider passing an object that exposes an interface that can acquire different model objects (kind of a locator class), but that probably causes more problems than it does fix them.

like image 163
Geoff Cox Avatar answered May 26 '23 11:05

Geoff Cox