Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
756 views
in Technique[技术] by (71.8m points)

asp.net mvc 3 - When to use ViewBag, ViewData, or TempData in Mvc3

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...