Friday, April 17, 2015

MVC - Passing the data

In ASP.MVC we have different techniques/types to pass data from Controller to View as well as Controller to Controller.


Below are the types we used

1. ViewData
2. ViewBag
3. TempData
4. Session

The first two ViewData and ViewBag are used to pass data from a controller to respective view. 

ViewData and TempData are dictionary of objects that are stored and retrieved using strings as keys. 

Just like that in ASP.Net Web applications, we can also use Session to persist data during a user session.

Lets explore one by one now.

1. ViewData
 
The syntax of ViewData is very similar to that of ViewState, SessionState and ApplicationState.
 
  •     ViewData is a dictionary object that is derived from ViewDataDictionary class.
  •     ViewData is used to pass data from controller to its corresponding view.
  •     ViewData is a property of ControllerBase class.
  •     It’s life lies only during the current request.
  •     If redirection occurs then it’s value becomes null.
  •     It’s required typecasting for getting data and it is always better to check for null values to   avoid error.

    // Storing data in ViewDataViewData["UserName"] = "LoginName";
    // Retrieving data from ViewDatastring strData = ViewData["UserName"].ToString();
    There is no compile time error checking with ViewData. 
     
    For suppose, if we there is any spelling mistake in key names we will not get any compile time error. 
     
    Hence we get to know about the error only at runtime.

    2. ViewBag

    • ViewBag is a dynamic property of the new dynamic features in C# 4.0.
    • Basically it is a wrapper around the ViewData and also used to pass data from controller to corresponding view.
    • ViewBag is a property of ControllerBase class.
    • It’s life also lies only during the current request.
    • If redirection occurs then it’s value becomes null.
    • It doesn’t required typecasting for getting data.

      // Storing data in ViewBag
      ViewBag.UserData = "UserDetails";
      // Retrieving data from ViewBagstring strData = ViewBag.UserData;

      3. TempData

    • TempData is a dictionary object that is derived from TempDataDictionary class and stored in short lives session.
    • TempData is a property of ControllerBase class.
    • TempData is used to pass data from current request to subsequent request (means redirecting from one page/controller to another).
    • It’s life is very short and lies only till the target view is fully loaded.
    • It’s required typecasting for getting data and check for null values to avoid error.
    • It is used to store only one time messages like error messages, validation messages.


      public ActionResult Index()
      {
        var model = new Review()
                  {
                      Body = "Review",
                      Rating=1

                  };
          TempData["MyModel"] = model;
          return RedirectToAction("ContactUs");
      }
      <pre><pre lang="cs">public ActionResult ContactUs()
      {
          var model= TempData["MyModel"];
          return View(model);
      }


      Session

      This is the last mechanism, Session, which work like the ViewData, like a Dictionary that take a string for key and object for value. This one is stored into the client Cookie and can be used for a much more long time. It also need more verification to never have any confidential information. Regarding ViewData or ViewBag you should use it intelligently for application performance. Because each action goes through the whole life cycle of regular asp.net mvc request. You can use ViewData/ViewBag in your child action but be careful that you are not using it to populate the unrelated data which can pollute your controller. 



    • In ASP.NET MVC, Session is a property of Controller class whose type is HttpSessionStateBase.

      1. public HttpSessionStateBase Session { get; }


    • Session is also used to pass data within the ASP.NET MVC application and Unlike TempData, it persists for its expiration time (by default session expiration time is 20 minutes but it can be increased).
    • Session is valid for all requests, not for a single redirect.
    • It’s also required typecasting for getting data and check for null values to avoid error.

No comments:

Post a Comment