Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Comparison of ViewData, ViewBag and TempData

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 331
    Comment on it

    Generally in ASP.NET MVC we use the ViewData,ViewBag, and TempData objects for the purposes of moving data beween views or from controller to views.In this post we compare them against each other higlighting there difference and usage patterns.

    Both the ViewData and ViewBag objects assume that the action returns a view and doesn't redirect.:

    a) ViewData is a dictionary object and is derived from ViewDataDictionary class whereas ViewBag is a dynamic property (a wrapper around ViewData)

    b) The scope of these objects lies only during the current request.

    c) In case of redirection the value becomes null for these objects

    d) They are used for moving Small amounts of data

    Below code sample illustrate the usage:

    ViewBag:

    public ActionResult Example()
    {
        ViewBag.Example = "Test";
        return View();
    }

    and in the view: @ViewBag.Example

    ViewData:

    public ActionResult Example()
    {
        ViewData["Example"] = "Test";
        return View();
    }

    and in the view: @ViewData["Example"]

    TempData object works well in scenarios where we need to pass data from current request to subsequent request:

    a) TempData is a property of ControllerBase class.

    b) It is used for passing data between the current and next HTTP request

    c) It is mostly used to store only one time messages like error messages

    Below code sample illustrate the usage:

    TempData:

    public ActionResult Example()
    {
        TempData["Example"] = "Test";
        return RedirectToAction("TestUrl");
    }

    and in the view: @TempData["Example"]

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: