I was editing a project and I saw a Session[“”] in one controller method and TempData[“”] in another. Is there a difference between the 4 or is it just 4 ways to do the same thing.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You set it in a controller action and use it in the view, then it disappears.
The difference is that the first is a dictionary whereas the second is just a
dynamicwrapper around this dictionary.Both point to the same data though.
ViewBag was introduced in ASP.NET MVC 3.
Example:
and inside the view you could use this value:
Same with ViewBag but it is dynamic:
and inside the view you could use this value:
So as you can see ViewData/ViewBag are just an alternative way to pass information to a view from a controller action compared to the classic and recommended way which is using a view model:
and then:
and inside your strongly typed view:
As you can see using view models provide a strongly typed approach in passing information to a view from a controller action.
Example:
ASP.NET MVC will automatically expire the value that was stored in
TempDataonce you read it. Under the covers ASP.NET MVC persists the information into theSession.