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

前端 未结 4 1373
时光说笑
时光说笑 2021-02-05 19:03

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 conside

相关标签:
4条回答
  • 2021-02-05 19:11

    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

    0 讨论(0)
  • 2021-02-05 19:16

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

    Hope this helps.

    0 讨论(0)
  • 2021-02-05 19:23

    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.

    0 讨论(0)
  • 2021-02-05 19:25

    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

    0 讨论(0)
提交回复
热议问题