Rectangle 27 13

The default TempData provider uses the session so there really isn't much of a distinction, except that your TempData is cleared out at the end of the next request. You should use TempData when the data needs only to persist between two requests, preferably the second one being a redirect to avoid issues with other requests from the user -- from AJAX, for example -- deleting the data accidentally. If the data needs to persist longer than that, you should either repopulate the TempData or use the Session directly.

I understand that. I put the meeting object in TempData in the GET method, then when the users posts the form, I should be able to retrieve it from TempData again, right?

No, you cannot count. TempData is for redirecting only. If you set TempData in a GET, then your page makes an AJAX call, then the user POSTs, the TempData is gone.

@Craig, I get your point. If I don't make any ajax requests, shouldn't it still be there, in my case?

I wouldn't bet on it. What if the user POSTs data, but it fails, because of server-side validation. So the POST returns a view, instead of redirecting. The user fixes the validation issue and POSTs again. The TempData is gone, because it was erased after the failed POST. Anyway, you probably use AJAX sooner or later, so don't plan around not using it. TempData really is for redirects only; this was confirmed to me privately by a member of the MVC team.

When to use TempData vs Session in ASP.Net MVC - Stack Overflow

asp.net-mvc session tempdata
Rectangle 27 13

The default TempData provider uses the session so there really isn't much of a distinction, except that your TempData is cleared out at the end of the next request. You should use TempData when the data needs only to persist between two requests, preferably the second one being a redirect to avoid issues with other requests from the user -- from AJAX, for example -- deleting the data accidentally. If the data needs to persist longer than that, you should either repopulate the TempData or use the Session directly.

I understand that. I put the meeting object in TempData in the GET method, then when the users posts the form, I should be able to retrieve it from TempData again, right?

No, you cannot count. TempData is for redirecting only. If you set TempData in a GET, then your page makes an AJAX call, then the user POSTs, the TempData is gone.

@Craig, I get your point. If I don't make any ajax requests, shouldn't it still be there, in my case?

I wouldn't bet on it. What if the user POSTs data, but it fails, because of server-side validation. So the POST returns a view, instead of redirecting. The user fixes the validation issue and POSTs again. The TempData is gone, because it was erased after the failed POST. Anyway, you probably use AJAX sooner or later, so don't plan around not using it. TempData really is for redirects only; this was confirmed to me privately by a member of the MVC team.

When to use TempData vs Session in ASP.Net MVC - Stack Overflow

asp.net-mvc session tempdata
Rectangle 27 5

You can use session state to persist data, TempData functionality use Session as default to persist the data.

You should minimise the use of session as much as possible, the reason for that is that a lock is taken on session for all request to prevent corruption of the session state, for example multiple Ajax requests will serialise because of this. More information here

You can use alternatives to persist data between request for example you can use the CookieValueProvider, which is part of MVC Futures to bind cookie data to model. You can also persist data in the actual DOM as hidden fields, but again these should be minimised as much as possible as the size of the data will be reflected in network traffic to and from the browser.

I would consider using another data store for your web application if your main store is slow. For example SQLServer CE or an embedded RavenDB.

They would synchronize not serialize.

Synchronization of parallel requests results in serialization (one after another)

To be clear, serial events are one after another, serialization generally refers to when one takes data in memory and puts it in a format that can be stored to disk.

Serialization doesn't mean one after another. I think the word you are looking for is "sequential" where multiple processes happen one after the other. Serialize is when an object is turned into raw bytes for something like "sending them over a stream" or "tcp/ip socket connection", or storing them on disk, etc etc. I think the proper word in the conext here is Sequentialization where a parallel algorithm or process turns into a series of sequential processes.

Why Session is a disaster in ASP.NET MVC application? - Stack Overflow

asp.net-mvc-3 session-state
Rectangle 27 46

It's been some time since I posted the question, which was quite colored by my little experience and knowledge of MVC. Still I received some quite useful input, that eventually led me to find a solution and also gain some insight of MVC.

What threw me off in the first place, was that you could have a controller with a strongly typed object as a parameter, like this:

public ActionResult DoSomething(MyClass myObject)...

This object originated from the same controller:

...
return View(myObject);
...

This lead me to believe that the object lived throughout these two steps, and that I somehow could expect that you could send it to the view, do something and then "magically" get it back to the controller again.

After reading up about model binding, I understood that this is of course not the case. The view is completely dead and static, and unless you store the information somewhere, it is gone.

Going back to the problem, which was selecting and uploading files from the client, and building up a list of these files to be displayed, I realized that in general there are three ways to store information between requests in MVC:

  • You can store information in form fields in the view, and post it back to the controller later
  • You can persist it in some kind of storage, e.g. a file or a database
  • You can store it in server memory by acessing objects that lives throughout requests, e.g. session variables

In my case, I had basically two types of information to persist: 1. The file metadata (file name, file size etc.) 2. The file content

The "by-the-book" approach would probably be to store the metadata in form fields, and the file contents in a file or in db. But there is also another way. Since I know my files are quite small and there will be only a few of them, and this solution will never be deployed in a server farm or similar, I wanted to explore the #3 option of session variables. The files are also not interesting to persist beyond the session - they are processed and discarded, so I did not want to store them in my db.

I was convinced. I simply created a sessionbag class as described in the article, and then I could do the following in my controller:

[HttpPost]
    public ActionResult AddImportFile(HttpPostedFileBase file)
    {

        ImportDataViewModel importData = SessionBag.Current.ImportData;
        if (importData == null) importData = new ImportDataViewModel();

        if (file == null)
            return RedirectToAction("DataImport");

        if (file.ContentLength > 0)
        {
            ImportDataFile idFile = new ImportDataFile { File = file };
            importData.Files.Add(idFile);
        }

        SessionBag.Current.ImportData = importData;

        return RedirectToAction("DataImport");
    }

I am fully aware that in most cases, this would be a bad solution. But for the few kb of server memory the files occupy and with the simplicity of it all, I think it worked out very nicely for me.

The additional bonus of using the SessionBag is that if the user entered a different menu item and then came back, the list of files would still be there. This would not be the case e.g. when choosing the form fields/file storage option.

As a final remark, I realize that the SessionBag is very easy to abuse, given the simplicity of use. But if you use it for what it is meant for, namely session data, I think it can be a powerful tool.

Good summary and explanation.

what about session expiring?

@garik a solution to deal with Sessions being recycled is using an Out-of-process session state server or sql server as per: technet.microsoft.com/en-us/library/cc754032(v=ws.10).aspx

action - ASP.Net MVC and state - how to keep state between requests - ...

asp.net-mvc action viewmodel state
Rectangle 27 35

The data you put in the ViewBag/ViewData is only available during the life-cycle of the request within which you populated it. MVC does not have post backs. If you need something to persist over more than a single request, you should use Session.

thanks for the reply. I had read that article and it does not touch on the lifecycle of ViewBag/ViewData but does slightly on TempData. To clear things up, by 'Post Back' all i meant was user submits a FORM thereby causing a HTTP POST Request, which is then handling by a Controllers appropriate Action method.

The article does state "However, once the controller redirects, the ViewBag and ViewData will contain null values." Correct, she doesn't specifically say that the ViewBag and ViewData's life-cycle ends once the request is complete, but she does imply it.

asp.net mvc 3 - ViewBag/ViewData Lifecycle - Stack Overflow

asp.net-mvc-3 viewbag
Rectangle 27 4

The problem with RedirectToAction is it's returning a HTTP 302 and the browser is then on it's own going and doing a brand new HTTP request. You may want to consider using a cookie and/or session object to persist the data between requests.

c# - MVC - Passing Data with RedirectToAction() - Stack Overflow

c# asp.net-mvc redirecttoaction
Rectangle 27 4

The problem with RedirectToAction is it's returning a HTTP 302 and the browser is then on it's own going and doing a brand new HTTP request. You may want to consider using a cookie and/or session object to persist the data between requests.

c# - MVC - Passing Data with RedirectToAction() - Stack Overflow

c# asp.net-mvc redirecttoaction
Rectangle 27 48

ASP.NET MVC TempData dictionary is used to share data between controller actions. The value of TempData persists until it is read or until the current users session times out. Persisting data in TempData is useful in scenarios such as redirection, when values are needed beyond a single request.

[HttpPost]
public ActionResult ApplicationPoolsUpdate(ServiceViewModel viewModel)
{
    XDocument updatedResultsDocument = myService.UpdateApplicationPools();
    TempData["doc"] = updatedResultsDocument;
    return RedirectToAction("UpdateConfirmation");
}

And in the ApplicationPoolController:

public ActionResult UpdateConfirmation()
{
    if (TempData["doc"] != null)
    {
        XDocument updatedResultsDocument = (XDocument) TempData["doc"];
            ...
        return View();
    }
}

Am I correct that TempData is not safe for use across several load-balanced servers unless I also put a shared session cache under it?

I still believe we should by all means avoid using session, in this case ViewData. They are not typed, and works only in In-proc session mode. For any load balanced server that uses State Sever or Sql Server session mode, the ViewData is lost.

c# - Passing data between different controller action methods - Stack ...

c# asp.net asp.net-mvc asp.net-mvc-3 asp.net-mvc-4
Rectangle 27 48

ASP.NET MVC TempData dictionary is used to share data between controller actions. The value of TempData persists until it is read or until the current users session times out. Persisting data in TempData is useful in scenarios such as redirection, when values are needed beyond a single request.

[HttpPost]
public ActionResult ApplicationPoolsUpdate(ServiceViewModel viewModel)
{
    XDocument updatedResultsDocument = myService.UpdateApplicationPools();
    TempData["doc"] = updatedResultsDocument;
    return RedirectToAction("UpdateConfirmation");
}

And in the ApplicationPoolController:

public ActionResult UpdateConfirmation()
{
    if (TempData["doc"] != null)
    {
        XDocument updatedResultsDocument = (XDocument) TempData["doc"];
            ...
        return View();
    }
}

Am I correct that TempData is not safe for use across several load-balanced servers unless I also put a shared session cache under it?

I still believe we should by all means avoid using session, in this case ViewData. They are not typed, and works only in In-proc session mode. For any load balanced server that uses State Sever or Sql Server session mode, the ViewData is lost.

c# - Passing data between different controller action methods - Stack ...

c# asp.net asp.net-mvc asp.net-mvc-3 asp.net-mvc-4
Rectangle 27 2

If your session is persisted in memory between requests, any other objects it references will be kept and not be eligible for garbage collection. There is no task that walks an object's internals setting references to null. Managed properties are only evaluated when the bean is created and before it is placed into scope.

Setting userBO to transient would only have an effect if the session was serialized (via passivation to disk, via session replication, etc.)

Session objects are no different from any other object in the VM in this regard. Hard references mean objects cannot be garbage collected. Perhaps you can set userBO to null after you are done with it (see also @PostConstruct.) Or perhaps you need to revisit your bean design if you are leaking objects out of scope - you could use a request-scope object to populate your session-scope object using userBO for example.

Thanks, I guessed the same. Apparently best option I see here is to make my ManagedBeans as requestScoped and manually set my session Objects :/

Inject your session objects into the relevant request objects.

That is exactly what I had done previously (injecting this session object) but then I realized that my userBO is also getting linked to my session object. So now I got to move my session objects into a separate class(sessionBean) and mark that as sessionScope, and inject that where ever required. Thanks again for the info :)

Does JSF store my helper class, which is referenced in my ManageBean i...

session jsf jsf-2 transient session-scope
Rectangle 27 10

TempData is like ViewData, except that it persists for two successive requests making it useful for things like passing data between two different controller actions

TempData in MVC actually persists until retrieved. As an FYI Tempdata is actually stored in a users SessionState so it is more like SessionData than ViewData

Essentially TempData is like a Session Property - (stored in the SessionState) used for communication between two successive requests to the controller. As if this is a good or bad practice well in your case I think it would be perfectly fine to pass data to the tempdata but their are other options, hidden fields among them. Another good link to look at is ASP.NET MVC - TempData - Good or bad practice

I think "TempData in MVC actually persists until retrieved" means that this is a safe pattern since the TempData has the GUID in the key. Do you agree?

Hmmm, no I don't think it does... Someone correct me if I'm wrong though this link "Persistence of TempData" might help stackoverflow.com/questions/3982465/ I believe its fine since it does keep track of them separately but you always have to be careful with the state its in.

c# - Proper use of TempData in ASP.NET MVC3? - Stack Overflow

c# jquery asp.net-mvc-3
Rectangle 27 7

TempData persist between two requests. What does the ReturnView method in your Edit action returns? As far as I can tell it is not a standard method defined in the Controller class. Are you redirecting in this method (i.e. returning a RedirectToRouteResult)?

Also are there any other requests that could occur between your Edit and Delete actions? For example ajax requests.

Generally it is not a good idea to use TempData to persist something for a long time. The pattern usually is the following:

public ActionResult Update() 
{
    // When you put something into the TempData dictionary you usually
    // redirect immediately to an action that will use the object stored
    // inside.
    TempData["something"] = "something";
    return RedirectToAction("success");
}

public ActionResult Success() 
{
    var something = TempData["something"];
    return View();
}

If you need to persist something for a longer time you should use Session.

I've edited the post, it was a typo, should have been return View() not returnview.

How about ajax requests that could invalidate TempData?

Fixed it, it was a problem with SessionState. Sorted it out with a few changes to the web.config.

I take it back, I added SessionState mode="InProc" into the SessionState but it's changed my nice looking URL's from localhost:4402/Route/Edit/1 to: localhost:4402/(S(e23msb30lb3u4vzbhlkhkajx))/Route/Edit/1 Any ways round this? I don't have any AJAX requests that invalidate TempData.

The "token" you see in the url is when you disable cookies for session tracking. Just set cookieless="false" in sessionState and your urls will be nice again.

asp.net mvc - TempData not persisting - Stack Overflow

asp.net-mvc tempdata
Rectangle 27 1

ASP.NET MVC TempData dictionary is used to share data between controller actions. The value of TempData persists until it is read or until the current users session times out. Persisting data in TempData is useful in scenarios such as redirection, when values are needed beyond a single request.

In your Register action you would have:

TempData["Role"] = Request["selectRole"];

In your Index action you would have:

ViewBag.IsTeacher = (TempData["Role"] != null && TempData["Role"] == "teacher");

Then in your view you would have:

... ViewBag.IsTeacher == true ...

No, TempData is to pass data between actions, ViewBag is between action and view. So in your second action have ViewBag.IsTeacher = (TempData["IsTeacher"] == "1");

I am facing this ERROR now: Object reference not set to an instance of an object. At line: @if (Request.IsAuthenticated && TempData["IsTeacher"].Equals("1")). System.NullReferenceException: Object reference not set to an instance of an object.

See edits, keep in mind == is case sensitive.

By home action you mean Index action method in my home controller ? or something else ?

asp.net mvc - Can't access value of view bag in view set in controller...

asp.net-mvc controller viewbag
Rectangle 27 12

No, viewstate is page specific. You will need to use something like a session variable or a querystring parameter to pass your state between pages.

c# - Is it possible to persist the viewstate between pages in ASP.NET?...

c# .net asp.net viewstate
Rectangle 27 11

@SessionAttributes enables persisting model attributes session between requests, and is meant to be specific per hanlder. The intent was to provide a construct that will be a step close towards implementing a conversation scope (shorter than session, longer than request). The need for conversational scope and why it is not fully available with @SessionAttributes is explained well in this blog.

It enables the automatic storing of the matching model attributes (match is based on the name). The default storage is HttpSession but this can be configured differently also. The docs say

Session attributes as indicated using this annotation correspond to a specific handler's model attributes, getting transparently stored in a conversational session. Those attributes will be removed once the handler indicates completion of its conversational session.

This bit however Those attributes will be removed once the handler indicates completion of its conversational session. does not happen automagically, and it is up to a developer to indicate the exit from the conversation by using setComplete on a SessionStatus instance. Otherwise the models attribute will remain in session, often an undesired side effect.

The easiest way to understand the difference is by observing the scope and the value of the model variable, model variable backed with @SessionAttribute, and the "normal" HttpSession variable.

Take a look at the two simple controllers

@Controller
@SessionAttributes("modelAndSession")
@RequestMapping("/sessionattr")
public class FirstController {
    protected static final String NEXT_VIEW = "next";
    @RequestMapping("/init")
    public String handlingMethod1( Model model, HttpSession session) {
        model.addAttribute(NEXT_VIEW, "/sessionattr/afterinit");
        session.setAttribute("session", "TRUE");
        model.addAttribute("modelAndSession", "TRUE");
        model.addAttribute("model", "TRUE");
        return "index";
    }

    @RequestMapping("/afterinit")
    public String handlingMethod2(SessionStatus status, Model model) {
        model.addAttribute(NEXT_VIEW, "/nosessionattr/init");
        //status.setComplete();
        return "index";
    }

}
@Controller
@RequestMapping("/nosessionattr")
public class SecondController {
    protected static final String NEXT_VIEW = "next";
    @RequestMapping("/init")
    public String handlingMethod3(Model model) {
        model.addAttribute(NEXT_VIEW, "/sessionattr/init");
        return "index";
    }
}

and the view that will trigger the flow

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<a href="${next}">Next step ${next}</a>
<hr/>
<table>
     <thead>
          <th>key</th> <th>Request scope</th> <th>Session scope</th>
     </thead>
    <tr>
        <td>model</td> <td>${requestScope.model}</td> <td>${sessionScope.model}</td>
    </tr>
    <tr>
        <td>model and session</td> <td>${requestScope.modelAndSession}</td> <td>${sessionScope.modelAndSession}</td>
    </tr>
    <tr>
        <td>session</td> <td>${requestScope.session}</td> <td>${sessionScope.session}</td>
    </tr>
</table>

Upon the initial request /sessionattr/init the view renders as follows

so the model variable is available in the request scope, the sessionattribute is available in both the request and the session scope and the "normal" session attribute available only in session scope

On the next request /sessionattr/afterinit the view renders as follows

so the model-only variable is gone, while the @SessionAttribute model attribute is pushed from the session to the model and persisted across requests. The next step will target a second controller /nosessionattr/init, and the view will render as follows

now the @SessionAttribute model object is gone from the model, but since the status.setComplete is not explicitely called it remained in the session as a normal variable

This is a specially confusing scenario as many expect that @SessionAttribute model object should be gone after switching handler, however unless explicitly cleared it remains in the session. Feel free to copy the snippets and investigate further the combination that confuses you

Why if i want to delete all the objects from httpsession i have to write session.invalidate() but if i want to delete all the object annotated by @Session attributes I have to write SessionStatus setComplete()?Are they stored in different places?I read the spring Api and it says "For permanent session attributes, e.g. a user authentication object, use the traditional session.setAttribute method instead" Why?

By default SessionAttributes are store in HttpSession (but this can be changed). Its not the matter of how they are stored, rather that they are a different things, SessionAttributes reads from the session, and stores to the model, and vice versa, so those are model attributes persisted in session. But session can hold other variables as well, that's why you have distinctive delete methods. SessionAttributes usually serves the purpose to persist data accross subsequent calls to the methods of the same contoller, as its scope is bound to the handler. While the scope of the session is wider

In my Spring MVC project I have annotated @SessionAttributes("user") in a controller .Why if ,in a method of the controller, i redirect to index.jsp(managed by another controller), I can see in this jsp the User's informations? Instead you said "serves the purpose to persist data accross subsequent calls to the methods of the same contoller".In my case the controllers are different..

the question deserved a better answer, what you're explaining is due to the fact that the jsp reads the info from the session. However, unless you second controllers also uses @SessionAttribute with the same key, the value won't be automatically pushed to model. Tried to explain it with the code

You said "They support a scope shorter than traditional session (the conversational scope)" Is This for @SessionAttributes or for Model attributes?

Spring: @SessionAttributes vs HttpSession - Stack Overflow

spring spring-mvc
Rectangle 27 1

In a web application, there are various ways a user can "leave" a page. The model of a web application is request based; client and server do not know of each other between requests. Some techniques as cookies or session state try to close this gap, but basically there is no connection. Therefore, the browser will not notify the server if the user leaves a page, so there is no such event as a Page_Leave. However, you could solve this for some cases (e.g. if the user changes to another page of your application), but not for all. As @Terror.Blade pointed out, session data is for data that needs to be persisted across a single pages lifecycle. Therefore I'd not suggest to put these data into the Session and find a (not very stable) way to delete it once the user leaves the page. As it seems it is not an option for you to request the DataTable again for the same user (though this is a common way). I can suggest you the following alternatives:

  • If the DataTable is not too big, as you know ViewState is an option that asserts that the data is not persisted across the page lifecycle.
  • You can also use the Cache to store the data. In contrast to Session state, the Cache has capabilities to free the memory after a certain time or if memory is required for more important data. However, be prepared that the data might need to be fetched again if it was removed from the Cache between requests. Also be aware that the cache is shared among all users and not limited to a Session, so you need to make sure that the users do not see information that is not intended for them. This can also be an advantage, if the DataTable is the same for several users, you can store it in the Cache once.

c# - asp.net free session variables on page change - Stack Overflow

c# asp.net session viewstate
Rectangle 27 8

If you don't want the parameter to be shown in the address bar you will need to persist it somewhere on the server between the redirects. A good place to achieve this is TempData. Here's an example:

public ActionResult Index()
{
    TempData["nickname"] = Person.nickname;
    return RedirectToAction("profile", "person");
}

And now on the Profile action you are redirecting to fetch it from TempData:

public ActionResult Profile()
{
    var nickname = TempData["nickname"] as string;
    if (nickname == null)
    {
        // nickname was not found in TempData.
        // this usually means that the user directly
        // navigated to /person/profile without passing
        // through the other action which would store
        // the nickname in TempData
        throw new HttpException(404);
    }
    return View();
}

Under the covers TempData uses Session for storage but it will be automatically evicted after the redirect, so the value could be used only once which is what you need: store, redirect, fetch.

True, could use this. But do you really wanted to be serializing/de-serializing (assuming non-In proc session) on a single redirect? If he's using forms auth he can fetch the user info from the ticket anyway.

thanks for all of your replies,my question is TempData gone after refresh the page and i got error.how can i handle this?

If you read TempData by using the Peek method it will persist for the next request. stringstr = TempData.Peek("Td").ToString(); Refer to the following article for more TempData details: codeproject.com/Articles/818493/

RedirectToAction usage in asp.net mvc - Stack Overflow

asp.net asp.net-mvc
Rectangle 27 4

Controllers are instantiated for each request. Once you request TimeSeriesData, the controller that was created for the request to Edit has already been disposed. If you need to hold on to a piece of data between requests, you must either put it in Session or TempData (both of which use sessions).

thats what I was afraid of... thank you!

can you take a look at this question for me as well if you don't mind? take a look at the comment I've left on the answer. stackoverflow.com/questions/26348680/

c# - private member in controller returns null after being set in acti...

c# asp.net asp.net-mvc entity-framework
Rectangle 27 1

Session
ViewState
Session["qno"] = (int)row["qno"];

How to take the the value from Session.

int qno = 0;
if(Session["qno"] != null)
   qno = int.TryParse(Session["qno"].ToString(), out qno);

c# - Global variable value not persisting on page postback in asp.net ...

c# asp.net .net pageload page-lifecycle
Rectangle 27 20

There is nothing un-MVC about Session, its a vital part of the web and most sites use it in some way. You really have two main options. Either store the object in the database between pages (which means saving an incomplete object) or put it in session. Both have advantages and disadvantages.

In session you don't have to save a partial object to the database, but if the user leaves or the session times out you lose all that information. It can also lead to a larger memory footprint per user and when you get to scaling it causes some other problems. (all of which can be solved using sticky-session on a load balancer or central session store).

The database way is better in lots of ways but usually you don't want to save incomplete object to the database, one compromise is to create another table and to save the object serialized to that table. Its not going through your real tables and so you don't have to compromise on your database constraints. (you can also store session data in the database which is basically doing the same thing)

In the end its a judgment call between the two ways, I have used both over the years.

I don't disagree with you, but be aware the sticky session or central session state are both bad news for scalability. It is still possible to scale of course, but it makes life hard. If session state can be avoided you're scaleability story is much nicer - perhaps this is why the OP is wary of it?

How do you define hard? I have scaled a number of systems using this method and didn't run into issues. It is very hard to avoid session completely, especially once you get into users logging in, etc.

Asp.Net MVC and Session - Stack Overflow

asp.net-mvc session-state session-variables