Wednesday, September 24, 2014

ViewBag ViewData and TempData in mvc asp.net

In Asp.net Mvc offer three ways to pass data from controller to view in next request. The most important question here when to use ViewBag   ViewData and tempData. You will use the ViewData, ViewBag, and TempData objects for the purposes of transporting small amounts of data from and to specific locations.
  Similarities between ViewBag & ViewData:
   Helps to maintain data when you move from controller to view.
    Used to pass data from controller to corresponding view.
    Short life means value becomes null when redirection occurs
  Differnec between ViewBag & ViewData:
ViewData is dictionary type object. It derived from  from viewdatadictionary  class
ViewData required typecasting and also check for null value to avoid the errors
Viewbag conatin the dynamic property  and it doesn’t  required typecasting
ViewBag was introduced in ASP.NET MVC 3

Example

     public ActionResult Index()
        {
            ViewBag.Message = "Your application description page.";//dynamic lis
            ViewData["Message"] = "Here is tesing";
            return View();
        }
Call on razor Page
<h2> @ViewBag.message</h2>

      @if(ViewData["message"] !=null)
      {
           <h2> @ViewData["message"</h2>
      }

TempData:

TempData is also a dictionary derived from TempDataDictionary class and stored in short lives session and it is a string key and object value. The difference is that the life cycle of the object. TempData keep the information for the time of an HTTP Request. This mean only from one page to another. This also work with a 302/303 redirection because it’s in the same HTTP Request. Helps to maintain data when you move from one controller to other controller or from one action to other action. In other words when you redirect, “Tempdata” helps to maintain data between those redirects. It internally uses session variables. Temp data use during the current and subsequent request only means it is use when you are sure that next request will be redirecting to next view. It requires typecasting for complex data type and check for null
public ActionResult Index()
        {
          

            TempData["Message"] = "Keep Global";

            return View();
        }
  @if (TempData["message"] != null)
        {
             <h2> @VTempData["message"].ToString() </h2>
         
        }

No comments:

Post a Comment

http://blogsiteslist.com