I read PRO ASP.NET MVC2 from Stephen Sanderson and I still can not figure out something about the session. In the book, he talks about how to design a session-based shopping cart using the Custom model binding for a long session. Everything is working fine, but I can’t understand how it works under the hood. Since this is cool code, I will 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 can see, there is an instruction for retrieving the contents of the Counter Counter = (Counter) controllerContext.HttpContext.Session [counterSessionKey] session; But for SAVING, there are no statements in the session. I would expect a subsequent statement somewhere: controllerContext.HttpContext.Session [counterSessionKey] = counter; But this code does not appear anywhere
.
- Counter ... , , .
, .