ChatGPT解决这个技术问题 Extra ChatGPT

ASP.NET MVC - TempData - Good or bad practice

I'm using the AcceptVerbs method detailed in Scott Gu's Preview 5 blog post for dealing with form entries in ASP.NET MVC:

User gets an empty form via GET

User posts the filled in form via POST to the same Action

The Action validates data, takes appropriate action, and redirects to a new view

So I don't have to use TempData. That said, I now have to add a 'confirm' step to this process, and it seems to require the use of TempData.

For some reason, I have an aversion to using TempData -- that it is something to be designed around.

Is this at all a valid concern, or am I making it up?

Consider making your 'confirm' step a javascript dialog. Less server-roundtrips and you won't run into this problem.

J
JasonD

No need to have an aversion to TempData... But if not used correctly it could surely be an indication of poor design. If you are using RESTful URL's, TempData is a best practice for transfering messages from your POST Actions to your GET Actions. Consider this:

You have a form at URL Products/New. The form Posts to Products/Create, which validates the form and creates the Product, On Success the Controller redirects to URL Products/1 and on error would redirect back to products/New to display Error Messages.

Products/1 is just the standard GET action for the product, but we would like a message to display indicating the insert was a success. TempData is perfect for this. Add the message to TempData in the Post Controller and put some if logic in the view and your done.

On failure I've been adding the values entered in the formCollection and a collection of error Messages to TempData in the Post Action, and redirecting to the intial Action Prodcuts/New. I've added logic to the view to populate the form inputs with the previously entered values along with any error messages. Seems nice and clean to me!


Why do that extra work when you can post directly back to Products/New? What value does Products/Create add?
@Mark, using Products/Create prevents the situation where the user completes the action via postback, then on a later refresh (or a bookmark & return) accidentally recompletes the action. For more, see en.wikipedia.org/wiki/Post/Redirect/Get
@ehdv: But does it really? On success it redirects to another page, on failure it should display the form errors and no action should be taken, so no harm done. It would only prevent that annoying "are you sure you want to re-post" message, which I often do want to. I guess it depends on your design though, so I can see your point.
J
John Rayner

I think you do well to hesitate before using TempData. TempData is stored in the session and this may have implications for you if:

You don't use sessions on your site right now You have a system that needs to scale to high throughput, i.e. you'd prefer to avoid session state altogether You don't want to use cookies (I don't know how well MVC supports cookieless sessions right now)

If your site needs to have high availability, then there are additional considerations around applying session state but these are all solvable problems.


TempData doesn't have to be stored in session, although it is the default provider - which is probably why it's not in the method doc. There's a cookie provider out there as well, as an example of how to write a custom provider.
F
Frank Schwieterman

I kind of think of temp data as being a fire-and-forget mechanism for notifying the user. Its great to give them a reminder of something they recently did, but I'd also be hesitant to make it a required step in some user process. The reason being if they refresh the page, I believe it would be gone. Well I guess I'm also hesitant to use it as its not really well defined how reliable it is.

I wonder if the problem is that you're having the action redirect to another page before the confirm step. I wonder if instead after they first submit, you could do enough processing to generate the confirm dialog, then return the original page with the confirm question. Similar to how you might do validation, except the validation rule checks whether the confirmation step was performed (with the confirmation UI hidden until other validation passes).


T
Todd Smith

I have a GetModel method which first checks for TempData["model"] and returns that. Otherwise GetModel loads the appropriate data from the database.

It saves an extra load from the database when I have an action that needs to return a different view that requires the same model data.


Yah, I have run into this: (1) validate a record exists, if valid, redirect to page (2) load record to display for user. So the database gets hit for validation and for display. I'm almost using TempData for this, but felt like checking opinions. I like your method to contain it though.
It would be better to use a proper caching mechanism in this scenario.
C
Community

Check out sessionless controllers in MVC3. It turned out, that using session prevents parallel execution of a single user's requests and thus leads to degraded performance.

Since tempdata uses session by default you wouldn't be able to use this feature. You can switch to using cookies for tempdata, but it's a bit awkward (at least for me). Still cleaner than viewstate, though, so maybe it's not such a big dealbreaker.


You are correct about Sessionless Controllers and TempData uses the Session. BUT WAIT! Session is NOT a bad thing and you can mix and match Sessionless with Session controllers. You really want Session_less_ controllers when you are doing lots of AJAX calls to the server (from the browser). When your just hitting one page -at-a-time- .. u don't need to be sessionless. In fact, that should NOT give you any benefit ... because you're only hitting the server ONCE. So it's possible to mix and match.
m
maxnk

Why do you have such an aversion? This thing is simply make its job and make it well :)

If you don't like it because of it non-strongly-typed, you can always make a wrapper around which will provide you strongly-typed interface.


M
Magnus Johansson

It's like using ViewData, meaning it's probably not a security risk. But i would rather use ViewData than TempData. Check here for a comparason: http://www.squaredroot.com/2007/12/20/mvc-viewdata-vs-tempdata/

Depending on the design, you could always store the user / basket or whathever you need in the tempdata in the database and just have a "IsReady" field which indicates if its completed or not, making it extensable for later if you want to take in mind, that people can close their browsers.


Note: the article you link to was up-to-date for its time, but is only accurate for MVC1. TempData changed pretty significantly in MVC2.
@mikemanne, yeah. But the answer is from late 2008. But maybe the answer should be updated?
W
Warren

All good answers, have you had a look at this for passing messages along.

TempData and Session arent the best idea for RESTful architectures as most sessions are stored in memory. So when you want to use a server farm, the users session would exist on one server while their next request could be sent to another server.

That being said have a look at this use of TempData for passing messages here.

http://jameschambers.com/2014/06/day-14-bootstrap-alerts-and-mvc-framework-tempdata/

Mabye this could be adapted to use a query string approach if used only for redirect to another page alerts.