Heavily Printed Items Viewbag

If I use a ViewBag that contains a strongly typed object, is there a way for MVC Razor to define (or apply this) so that all elements of this object appear in IntelliSense?

For example, let's say I have

ViewBag.Movies.Name ViewBag.Movies.Length 

I know that movies have a Movie object type that has members Name and Length

 class Movie { public string Name {get; set;} public string Length {get; set;} } 

Can I somehow apply this as I do for the model

 @model Transactions.UserTransactionDetails 

To make movie members available at Razor?

+4
source share
4 answers

Use a ViewModel that contains properties for all the objects you are viewing,

eg.

 public class MovieTransactionViewModel { public List<Transaction> Transactions { get; set; } public List<Movie> Movies { get; set; } } 

Then, if your view uses this as a model, and you get intellisense in your view.

This way you do not change your models, so EntityFramework will not be affected.

+11
source

You can save it in a variable.

 var movie = (Movie)ViewBag.Movie; 

Then typing @movie. , you will get intellisense for Name , Length .

+12
source

Stay away from VieWbag: http://completedevelopment.blogspot.com/2011/12/stop-using-viewbag-in-most-places.html

Just create a new VieWModel containing other models inside it.

+2
source

Not. This is because the ViewBag is not very typed. It is implemented using dynamics and ExpandoObject. If you need a strongly typed model, why not use it?

+1
source

All Articles