Monday 12 January 2015

ViewData VS ViewBag Vs TempData in MVC

Introduction
In Asp.Net MVC there are three ways to pass/store data between the controllers and views.

ViewData
  1. ViewData is used to pass data from controller to view
  2. It is derived from ViewDataDictionary class
  3. It is available for the current request only
  4. Requires typecasting for complex data type and checks for null values to avoid error
  5. If redirection occurs, then its value becomes null
ViewBag
  1. ViewBag is also used to pass data from the controller to the respective view
  2. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0
  3. It is also available for the current request only
  4. If redirection occurs, then its value becomes null
  5. Doesn’t require typecasting for complex data type
TempData
  1. TempData is derived from TempDataDictionary class
  2. TempData is used to pass data from the current request to the next request
  3. It keeps the information for the time of an HTTP Request. This means only from one page to another. It helps to maintain the data when we move from one controller to another controller or from one action to another action
  4. It requires typecasting for complex data type and checks for null values to avoid error. Generally, it is used to store only one time messages like the error messages and validation messages
  5. Keep and Peek methods are used to preserve/get value of Tempdata using-tempdata-peek-and-keep-in-Asp-Net-mvc/

Example :   
 
Controller Action: 
public ActionResult Index()
    {
      var model = new LoginModel()
      {
          UserName = "hello",
          Password="1",
          RememberMe =true
      };
      List<LoginModel> log = new List<Models.LoginModel>();
      log.Add(model);
      TempData["ModelName"] = log;
      ViewBag.Name = log;
      ViewData["Name"] = log;
      return View();
    }

View : 
<ul>
    @foreach (var item in TempData["ModelName"] as List<mvc1.Models.LoginModel>)
    {
        <li>
            @item.UserName
        </li>
    }

</ul>
<br />
<ul>
    @foreach (dynamic item in ViewBag.Name)  @*No Typecast*@
    {
        <li>
            @item.UserName
        </li>
    }

</ul>
<br />
<ul>
    @foreach (var item in ViewData["Name"] as List<mvc1.Models.LoginModel>) @*Typecast*@
    {
        <li>
            @item.UserName
        </li>
    }
</ul>


0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives