问题
Can somebody please explain the purpose of TempData in MVC. I understand it behaves like ViewBag but what does it do beyond that.
回答1:
TempData is meant to be a very short-lived instance, and you should only use it during the current and the subsequent requests only! Since TempData works this way, you need to know for sure what the next request will be, and redirecting to another view is the only time you can guarantee this. Therefore, the only scenario where using TempData will reliably work is when you are redirecting. This is because a redirect kills the current request (and sends HTTP status code 302 Object Moved to the client), then creates a new request on the server to serve the redirected view. Looking back at the previous HomeController code sample means that the TempData object could yield results differently than expected because the next request origin can't be guaranteed. For example, the next request can originate from a completely different machine and browser instance.
http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applications
回答2:
ViewBag
Allows you to create dynamic properties
Passing data between the controller and view
Controller
ViewBag.Name= "Lion";
View
<div>
<h4>@ViewBag.Name</h4>
</div>
TempData
TempData is meant to be a very short-lived instance
you should only use it during the current and the subsequent requests only
TempData dictionary is used to share data between controller actions
TempData["Name"] = "Lion";
I have written Blog post about this.Check that How to use Asp.Net MVC TempData Properly ?
回答3:
TempData is a dictionary object that is derived from TempDataDictionary class and stored in short lives session.
public TempDataDictionary TempData { get; set; }
It is a property of ControllerBase class.It is used to pass data from current request to subsequent request (means redirecting from one page to another). It’s life is very short and lies only till the target view is fully loaded. It’s required typecasting for getting data and check for null values to avoid error.It is used to store only one time messages like error messages, validation messages.
来源:https://stackoverflow.com/questions/10487008/mvc-c-sharp-tempdata