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?
You could store it in a variable.
var movie = (Movie)ViewBag.Movie;
Then typing @movie.
will produce intellisense for Name
, Length
.
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.
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.
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?
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