ViewData, ViewBag and TempData in ASP.NET MVC

 

ViewData, ViewBag and TempData in ASP.NET MVC

Hi Folks,

In this blog we are discussing about how to pass data from controller to view or controller to another controller.

1

In MVC data will be passed by using ViewData ViewBag and TempData . 

their are some scenarios.

1. pass data from controller to view.

2. pass data from one action method to another action method in a controller.

3. pass data from one controller to another controller.

You can follow my previous blogs for the code we are following step by step.

https://webdevelopmentknowledge.blogspot.com/2020/10/routing-in-aspnet-mvc.html

ViewBag :

ViewBag is used to pass data from controller to View. It is dynamic type no typecast and no null check required when using ViewBag object. ViewBag scope is for the request from controller to View.

Controller:


2

View:

3


Output:

4


ViewData:

This is a dictionary object used to pass data from controller to View. For this typecast and null check is mandatory else you will end up in null exceptions.
ViewData scope is for the request from controller to View.

Controller:


Controller

View:

View


Result:
Result

TempData:

This is a dictionary object used to pass data from controller to controller and action methods with in a controller and this expiry will be remain for subsequent request if you want to use it further you should use Keep or Peek . For this typecast and null check is mandatory else you will end up in null exceptions.
Tempdata

Tempdata will be useful in real time to maintain the session of a user data.

Conclusion ViewBag and ViewData used to pass data from controller to View expires after your request. TempData used to pass data from controller to controller method to method and expires after subsequent request.

This are all the different types of data parsing ways used in MVC but in real time we don't use this much because it is loosely typed . if any null values not handled or any syntax error you cannot catch at compile time it will throw error in run time.

To resolve this in real time project people prefer using strongly typed views. we will discuss about strongly typed views in next blog.

Thanks for reading! catch you up in next blog. Any doubts feel free to reach out.

Post a Comment

2 Comments

  1. Informative man.
    I didn't know these.
    I was just copy paste older code.

    I learnt now. Thanks for posting.
    Keep posting...

    ReplyDelete
    Replies
    1. Thanks Mukesh. we will be posting more posts with more information. Thanks for reading.

      Delete