I've been reading PRO ASP.NET MVC2 by Steven Sanderson and I still can't figure out something about session. In the book he tells how to develop a Cart based on session using a Custom model binder for session persisting. Everything works fine but I can't figure out how it really works under the hood. Since it's a fair amount of code I'll write a simplified version
Counter
public class Counter
{
public int counter = 0;
public void Increment(){
counter++;
}
}
CounterController
public ActionResult Index(Counter counter)
{
counter.Increment();
return View(counter);
}
CounterCustomModelBinder
public class CounterCustomModelBinder: IModelBinder
{
private const string counterSessionKey = "_counter";
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
Counter counter = (Counter)controllerContext.HttpContext.Session[counterSessionKey];
if (counter == null)
{
counter = new Counter();
controllerContext.HttpContext.Session[counterSessionKey] = counter;
}
return counter;
}
}
Global.asax
...
ModelBinders.Binders.Add(typeof(Counter), new CounterCustomModelBinder());
As you see there's a statement for fetching the session contents Counter counter = (Counter)controllerContext.HttpContext.Session[counterSessionKey]; But there's no statement for SAVING into session. I would expect the subsequent statement somewhere: controllerContext.HttpContext.Session[counterSessionKey] = counter; But this code doesn't appear anywhere
Nevertheless it still works. Somehow when updating the Counter object, the session gets updated Automagically... But I can't understand where when and HOW. Thanks to anyone will reply.