When is it “acceptable” to use ViewBag/ViewData in

2020-05-26 12:52发布

问题:

I realize that the best practice is to use strongly typed Views and pass in all needed data in a ViewModel, but I am curious if there are situations where it is actually considered "best practice" to pass data in the ViewBag/ViewData.

In what scenarios is the ViewBag/ViewData preferred for passing data to a view?

update

It's great to hear the various uses everyone has come up with for ViewBag/ViewData. We may never arrive at a "best practice" but it will be great to see the different solutions people have come up with that rely on the ViewBag/ViewData.

回答1:

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



回答2:

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

Hope this helps.



回答3:

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.



回答4:

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

<%:Html.DropDownList("GetIDHere", new SelectList((IEnumerable<someModel>)ViewData["xyz"]),"select Author")%>

Then you put UIHint attribute on BookID field of your model for instance

public class Book
{
    public int BookID{get;set;}
    [UIHint("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