ViewModels or ViewBag?

后端 未结 2 545
野性不改
野性不改 2020-11-29 09:23

I\'m fairly new to MVC4, EF5 and ASP.Net, and I don\'t seem to be able to find a good answer anywhere.

Basically, Should everything be done through the viewmodel or

2条回答
  •  猫巷女王i
    2020-11-29 09:37

    Prefer ViewModels over the ViewBag wherever you can. Create Strongly typed views. It makes your code cleaner, less fragile, less error-prone, and easy to maintain.

    ViewBags are just dictionaries of dynamically typed objects so you lose:

    • Compile time checking
    • The ability to refactor with confidence (you lose the support of the tools)
    • IDE support - such as the ability to navigate to all usages
    • Intellisense

    For bonus points making extensive use of the ViewBag also misses the point of using the MVC pattern

    I get the impression ViewBags were created to solve an edge-case problem in asp.net and people use them instead of creating view models as was originally intended in the design of the platform, to the detriment of their work.


    with thanks to Why not to use ViewBag heavily?

提交回复
热议问题