MVC ViewBag Best Practice

前端 未结 10 1922
野趣味
野趣味 2020-11-29 01:42

For the ViewBag, I heard it was a no-no to use. I would assume have the content from the ViewBag should be incorporated into a view model?

Question:

  1. <
10条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-29 02:21

    If there were no use cases for it, it wouldn't be implemented in the first place. Yes you can do everything with ViewModels, but what if you don't really need one? One such scenario is editing entities. You can pass DTO directly as a model.

    @model CategoryDto
    

    But what if you want to select Category parent? Entity DTO ideally holds only it's own values, so to populate select list you use ViewBag

    
    

    Why do this? Well if you have 50 types of entities each with some sort of select from different values, you just avoided creating 50 extra ViewModels.

提交回复
热议问题