12

When to use ViewBag, ViewData, or TempData in view. In the controller i want to send object to the view.I want to know that which will be best in this case. I want the object in the view page.

1

2 Answers 2

33

Use TempData when you need data to be available for the next request, only.

TempData["myInfo"] = "my info";

Then in the next request, it will be there... but will be gone after that.

Use ViewBag for most of your extra-data needs to pass to your view, beyond the @model

ViewBag.MyInfo = "my info";

Then access it from your view.

Use ViewData to access/enter the exact same info as ViewBag, except as a collection instead of properties of a dynamic object.

ViewData["MyInfo"]

accesses exactly the same data as ViewBag.MyInfo

Note that I used strings, but these can store any object you wish.

Another thing to note: TempData and ViewData are both dictionaries that store object values, so you must cast those to their original type when you use them. ViewBag however uses dynamic, and you don't always need to cast that, since it is done at runtime. Some methods (like Extension methods) can not handle dynamic though, so you would need to cast in those cases.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks I understand the usage
It is also worth remembering that TempData uses Session and is therefore not reliable on web farm unless the web farm uses sticky sessions or out-of-process session state. If the next request is bounced to another machine, your session may not be available.
May i add a point about TempData from here stackoverflow.com/a/17199709/2015869 ?
25

IMHO for decent design practies -

ViewBag = never. ViewData = never. These are magic string-ish based fields and canot be caught during any compile time instances either.

Your VieWModel should contain everything it needs. Thats it's purpose in life. Don't devoid it of its purpose. TempData for status messages only or object you don't want to cache but wan't available for the very next request only.

2 Comments

I cannot really even think of a good reason to use Temp Data.
The fact it relies on session object as well is caution to stay away from it, but some really like its use for passing a status message to the next page without having to worry about url passing/encoding.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.