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

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

ADO .Net (2) Ajax (1) Angular Js (17) Angular2 (24) ASP .Net (14) Azure (1) Breeze.js (1) C# (49) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DI (3) Dotnet (21) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (9) Lamda (3) Linq (11) Mongodb (1) MVC (48) NodeJS (7) RDLC (1) Report (1) Sql Server (29) SSIS (3) SSRS (2) UI (1) WCF (12) Web Api (10) Web Service (1) XMl (1)