我正在尝试将会话对象转换为模型,如下所示:
@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 :(得分:2)
只是添加一个东西,在绑定对象之前总是检查Session是否为null,所以如果任何一点会话被任何原因杀死它就不会给你一个分页符说NULL异常或者什么......