In the MVC (Model-View-Controller) architecture, TempData and ViewData are two mechanisms provided by ASP.NET MVC to pass data between a controller and a view.
TempData is a dictionary object that is available for the current request and the subsequent request. It is typically used to store data temporarily between actions. For example, if you redirect to another action from your current action, you can use TempData to pass data to the redirected action. Once the redirected action has processed the data, the TempData is cleared automatically.
ViewData, on the other hand, is a dictionary-like object that is used to pass data from a controller to a view. The ViewData dictionary is available only for the current request, and it is not available for subsequent requests. It can be used to transfer data between the controller and the view by adding key-value pairs to the ViewData dictionary in the controller, and then accessing the values in the view using the same keys.
Here is an example of how to use TempData and ViewData in an ASP.NET MVC controller:
csharppublic class ExampleController : Controller
{
public IActionResult Index()
{
// add data to the ViewData dictionary
ViewData["message"] = "Hello from the controller!";
// add data to the TempData dictionary
TempData["message"] = "This message will be available in the next action.";
return View();
}
public IActionResult NextAction()
{
// get data from the TempData dictionary
var message = TempData["message"];
// the TempData dictionary is automatically cleared
// after it has been accessed in the current or next request
return View();
}
}
In the Index action, data is added to both the ViewData and TempData dictionaries. In the NextAction action, the data is retrieved from the TempData dictionary. Note that the TempData dictionary is automatically cleared after it has been accessed in the current or next request.
Comments
Post a Comment