ViewBag, ViewData, TempData, Session - how and when to use them?

后端 未结 4 1684
被撕碎了的回忆
被撕碎了的回忆 2021-02-07 10:07

ViewData and ViewBag allows you to access any data in view that was passed from controller.

The main difference between those two is the way you are accessing the data.

4条回答
  •  悲哀的现实
    2021-02-07 10:50

    In simple terms:

    ViewBag is a dynamic (dynamic: ability to assign more than one value by different programs on the same object) object which is used to send data from controller to view. It can be used when we jump from controller's action to some view. However the value which we get in the view(in the viewbag object) can not be further replicated in other view/controller/js page etc. Meaning: Controller->View (possible). Now this value can not be send to next view/controller. Meaning Controller->View->View/controller/some js file (not possible), to carry this value you need to define some other variable and store viewbag value into it and then send it as a parameter.

    Tempdata is very much different than viewbag. It has nothing to do with view at all. It is used when we send data from one action(method) to other action in the same controller. That's the reason we use RedirectToAction whenever sending tempdata value from one action to another. Value of tempdata are not retained when send from controller to veiw (because it is not meant to do so).

    ViewData is simillar to viewbag but is a dictionary object. ViewData may require type casting while viewbag may not. It depends on the user which one he may want to use.

提交回复
热议问题