2011-05-17 67 views
2

我想如下的会话对象转换为模型:转换Session对象强类型对象在asp.net mvc的

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

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

,并尝试访问它。但我做错了什么。

这是粘合剂,如果你需要看到它(这工作正常):

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; 
    } 
} 
+0

你得到什么错误?.. – 2011-05-17 19:36:03

+5

尝试'@ {ShoppingCart cart =(ShoppingCart)Session [CartModelBinder。 CartSessionKey]; var foo = cart.Prop1}' – 2011-05-17 19:39:32

+0

谢谢,工作。 – 2011-05-17 19:53:17

回答

2

而只是为了补充说明一两件事,经常检查会话中的not null结合它的对象之前,因此,如果任何点会话被任何原因杀死,它不会给你一个分页符说NULL的例外或...