Question

I've an MVC3 web app. In that I've been using the PRG (Post-Redirect-Get) pattern. That is during postback if any model validation fails I persist the ViewData in TempData and then redirect to the original GET action.

In post action -

if (!ModelState.IsValid)
    TempData["ViewData"] = ViewData;

Later in the GET action -

if (TempData["ViewData"] != null)
    ViewData = (ViewDataDictionary)TempData["ViewData"];

This is pretty much the usual practice. Everything has been working fine till date. Now, we need to improve session persistence that is we need "longer" sessions. I've concluded to use ASP.Net State Server.

After I migrated my session to State Server -

web.config - 
<system.web> ... 
<sessionState timeout="180" mode="StateServer" cookieless="UseCookies" />  
...

I started getting "unable to serialize" errors for some of my sessions which stored custom objects. I've made such objects [Serializable] which sorted out the issue. But now I'm stuck with the above PRG pattern!

Error - Type 'System.Web.Mvc.ViewDataDictionary' in Assembly 'System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' is not marked as serializable.

Strange I'm not able to find a single thread which share my scenario. Any one?

Was it helpful?

Solution

The fact that TempData is stored in session and my session is in turn stored in external process demands that anything being stored must be "Serializable".

Objects like ViewDataDictionary or even ModelStateDictionary are NOT [Serializable]. For MVC PRG I just need to pass the modelstate errors and the invalid object.

I've already marked the object as [Serializable] (I'm using xml serializer to "stringify" my obj and then store it - because its a L2S Entity so need to avoid circular refs as well). Ref SO Post

TempDate["modelToPass"] = Serialization.Serialize<MyModel>(modelToPass);

And likewise I can translate my ModelState object (only for the errors) into a "simpler" object and transform it into something like

KeyValuePair<string,List<string>>[]

In short, I'm trying to make my modelstate and modelObject "serializable" so that I can put them in TempData and persist the PRG pattern.

There're some other approaches to deploy our own TempData and store TempData in cookies, etc.. but I don't want to complicate things. Do let me know if anyone has a better solution to this.

Some Ref urls

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top