2011-05-17 70 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的例外或...