Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strongly typed Viewbag items

If I am using a ViewBag which contains a strongly typed object, is there any way on MVC Razor to define (or cast this) so that all the elements of that appear in the IntelliSense?

For example lets say I have

ViewBag.Movies.Name
ViewBag.Movies.Length

I know Movies is of object type Movie, which has the members Name and length

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

Can I somehow cast this, like I do for model

@model Transactions.UserTransactionDetails

So that the members of Movie become available in Razor?

like image 665
John Mitchell Avatar asked Jun 18 '12 20:06

John Mitchell


4 Answers

You could store it in a variable.

var movie = (Movie)ViewBag.Movie;

Then typing @movie. will produce intellisense for Name, Length.

like image 146
Terry Avatar answered Oct 07 '22 12:10

Terry


Use a ViewModel, which contains properties for all the different objects that you view needs

e.g.

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

Then, have your view use this as it's model, and you will get intellisense in your view.

That way you are not changing your models, so EntityFramework will not be affected.

like image 32
StanK Avatar answered Oct 07 '22 13:10

StanK


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

Simply create a new VieWModel that contains other models within it.

like image 3
Adam Tuliper Avatar answered Oct 07 '22 14:10

Adam Tuliper


No. That is because ViewBag is not strongly typed. It is implemented using dynamics and ExpandoObject. If you need a strongly typed model, why don't you use one?

like image 1
alexn Avatar answered Oct 07 '22 13:10

alexn