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

前端 未结 4 1383
时光说笑
时光说笑 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: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)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

提交回复
热议问题