Shawn Mclean
Shawn Mclean

Reputation: 57469

Convert Session object to strongly typed object in asp.net mvc

I'm trying to convert a session object to a model as follows:

@ShoppingCart cart  = (ShoppingCart)Session[CartModelBinder.CartSessionKey];
@cart.Prop1 // <-- I cannot access 'cart'.

Error: CS0118: 'Econo.WebUI.Models.ShoppingCart' is a 'type' but is used like a 'variable'

and also try to access it. But I'm doing something wrong.

This is the binder if you need to see it (which works correctly):

public class CartModelBinder : IModelBinder
{
    public static string CartSessionKey { get { return cartSessionKey; } }         
    private static string cartSessionKey = "_cart";
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if (bindingContext.Model != null)
            throw new InvalidOperationException("Cannot update instances");
        ShoppingCart cart = (ShoppingCart)controllerContext.HttpContext.Session[cartSessionKey];
        if (cart == null)
        {
            cart = new ShoppingCart();
            controllerContext.HttpContext.Session[cartSessionKey] = cart;
        }
        return cart;
    }
}

Upvotes: 2

Views: 2106

Answers (1)

Safran Ali
Safran Ali

Reputation: 4497

And just to add one thing, always check the Session for not null before binding it the object, so if any point Session got killed by any reason it won't give you a page break saying NULL exception or something ...

Upvotes: 2

Related Questions