Properties that Are Alive on A Single Page Request
I have an ASP.NET MVC page, and inside the page I will make a few AJAX call.
What is the property inside the Contr开发者_高级运维oller
whose values are persisted as long as the page is still there ( even during AJAX call), and are destroyed when I switch to other page request?
Controller.Session
's keys and values, as we all know it, are alive and accessible all the time. Controller.Request
are alive when the page is constructed or when an AJAX call is made. Request
variables don't persist from a normal page call to subsequent AJAX call at the same page.
Any ideas?
persisted as long as the page is still there
A page is never truly "there". In ASP.NET MVC there is no concept of pages at all. Pages in the sense of interface entities with the lifespan stretching over several requests with the ability to persist some data and the controls state. There are views which only exist for a single moment with no ability to persist any data.
There are requests. You requested a page you've got it. Server has returned it to you and immediately forgotten about it. Your Ajax call is a completely new request. The server won't even know if it's an Ajax request. For it, all requests are equal, Get, Post or otherwise.
You can use the TempData collection, it will persists the data between two consequent requests.
The other alternative is the Session collection. It will keep data between many request of your session.
AJAX requests are totally seperate HTTP requests that are made to your server, keeping that in mind, here is a quick overview of the various server collections:
HttpContext.Current.Application
: Application level cache collection, is the same across every web request, regardless of where that web request came from
HttpContext.Current.Cache
: Cache collection, is the same across every web request, regardless of where that web request came from
HttpContext.Current.Request
: Request collection, contains querystring parameters, posted values and submitted cookies. This will vary for every HTTP request so will be different between the initial request and the subsequent AJAX requests.
HttpContext.Current.Items
: Collection for storing data between components used on a single web request, and so is dropped after a request is complete and will be reset between the original request and the AJAX requests
HttpContext.Current.Session
: Tied to a particular browser session (using cookies by default) so is the same for each distinct user that accesses your server. This is your only true option for what you want to accomplish
Values you find in the Request
property are fetched either from the URL or the POST body, so if they are not present when you perform the AJAX call, even if they were present when the original page was requested, they will no longer be available. The only property that is available across different requests is the Session
and TempData
(which uses the session to persist values between two requests).
精彩评论