What is difference between TempData and ViewData with syntax

Forums ASP.NET MVCWhat is difference between TempData and ViewData with syntax
Staff asked 2 years ago

Answers (1)

Add Answer
Umang Ramani Marked As Accepted
Staff answered 2 years ago

ViewData is a dictionary object used to send data from the Controller to the View.

The current request is allowed within the scope of ViewData. While redirecting, ViewData will become null.

Ex:

Public ActionResult Index()  
  {  
    ViewData[”Title”] = “Welcome”;  
    return View();  
  }

View:

<h2>@ViewData[“Title”]</h2>

 

Tempdata :

Tempdata is a dictionary object used to transmit data from one action to another in the same or other Controllers.

The scope of Tempdata is extended to the next request, and we should utilize Keep and peek if we want Tempdata to be available even longer.

Tempdata will not be null until the request is redirected.

 

Ex:

"Public ActionResult Index()  
  {  
    TempData[”Data”] = “I am from Index action”;  
    return View();  
  }  

  Public string Get()  
  {  
    return TempData[”Data”] ;  
  }

 

Subscribe

Select Categories