MVC C# TempData

2019-02-08 04:58发布

Can somebody please explain the purpose of TempData in MVC. I understand it behaves like ViewBag but what does it do beyond that.

3条回答
姐就是有狂的资本
2楼-- · 2019-02-08 05:22

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楼-- · 2019-02-08 05:25

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

查看更多
迷人小祖宗
4楼-- · 2019-02-08 05:26

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.

查看更多
登录 后发表回答