When is it “acceptable” to use ViewBag/ViewData in ASP.NET MVC?

I use them rarely, for bits of information that are totally unrelated to the model or view model that I'm passing to the view, again, most of the times I use a view model.

The only scenario I can see when you'd have information that doesn't belong in the ViewModel is if you're passing information to the Layout of your View. For this scenario, I like the usage of a base ViewModel, inherited by the ViewModels belonging to all Views that use a particular Layout. – SamStephens Sep 5 at 4:53.

I prefer to use some DTO instead of using viewbag. Using DTO make you strong type your viewdata. Hope this helps.

– stephen776 Apr 12 at 15:50 This is what I do I strongly type my view, with DTOs. I try to avoid using viewbag. But in some case like errors you can pass them to the viewbag – alexl Apr 12 at 15:53.

I can't say about best practice but I mostly use it when using Editor Templates. E. G if I want to display a dropdown list for editing certain field I make following editor template )ViewData"xyz"),"select Author")%> Then you put UInt attribute on BookID field of your model for instance public class Book { public int BookID{get;set;} UInt("mytemplate") public int AuthorID{get;set;} } in such cases, I assume, its particularly fine and clean to use ViewData.

This is the way Telerik asp. Net mvc projects have coded in their demo projects demo.

There's an argument to be made here for instead using a ViewModel, with a Book property and a IEnumerable property, giving you strong typing. – SamStephens Sep 5 at 4:31.

I typically will use a strongly typed view for displaying any content but will often set ViewBag. Member to the currently logged in member so that it can be used in the main Layout in addition to the specific view. I have an attribute called PopulateMemberContext which populates ViewBag.

Member and I add that attribute to my base controller so that every view will always have the necessary data. "Right" or "Wrong" I don't know - but it works wonderfully.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions