MVC ViewBag, ViewData, or TempData


  • ViewData
    • ViewData is a dictionary object that you put data into, which then becomes available to the view. ViewData is a derivative of the ViewDataDictionary class, so you can access by the familiar "key/value" syntax.
  • ViewBag
    • The ViewBag object is a wrapper around the ViewData object that allows you to create dynamic properties for the ViewBag.(Dynamic mean variable type define in reun time ex var)

  • TempData object works well in one basic scenario:
    • Passing data between the current and next HTTP requests (Data between one request to another)
    public class HomeController : Controller
    {
        // ViewBag & ViewData sample
        public ActionResult Index()
        {
            var featuredProduct = new Product
            {
                Name = "Special Cupcake Assortment!",
                Description = "Delectable vanilla and chocolate cupcakes",
                CreationDate = DateTime.Today,
                ExpirationDate = DateTime.Today.AddDays(7),
                ImageName = "cupcakes.jpg",
                Price = 5.99M,
                QtyOnHand = 12
            };
        
            ViewData["FeaturedProduct"] = featuredProduct;
            ViewBag.Product = featuredProduct;
            TempData["FeaturedProduct"] = featuredProduct;  
        
            return View();
        }
    }



    <div>
        <a href="/Products">
        <img src='@Url.Content("\\Content\\Images\\cake.jpg")' alt="Fourth Coffee Bakery"/>    
        </a>
        <div>
            Today's Featured Product is!
            <br />
            <h4>@ViewBag.FeaturedProduct.Name</h4>
            <h3>@viewDataProduct.Name</h3>
            <h2>@tempDataProduct.Name</h2>
        </div>
        @Html.ActionLink("Test Tempdata","Featured")
    </div>
    Temp Data


        TempData["FeaturedProduct"] = featuredProduct;
     
        //After the redirect, the ViewBag & ViewData objects are no longer available
        //Only TempData survives a redirect
     
        return new RedirectResult(@"~\Featured\");
    
    
    @using FourthCoffee.Models;
    @model FourthCoffee.Models.Product
    @{
        ViewBag.Title = "Details";
        var featuredProduct = TempData["FeaturedProduct"] as Product;
    }
    
    
    
    
    Read more :http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applications


    Comments

    Popular Posts