【发布时间】:2012-06-21 15:58:37
【问题描述】:
我已经为我的 MVC3 应用程序编写了Custom model binder。我决定使用自定义模型绑定器是因为我正在使用 Sessions 并且单元测试因此而失败。
现在我的问题是About 操作不接受任何参数,但它需要将存储在购物车中的值传递给查看而不使用会话。因为使用会话它将无法通过单元测试。模型绑定器仅在我将购物车作为参数传递给 About 时才有效。
如果您有任何想法,请建议我。
非常感谢
模型绑定器
public class CartModelBinder : IModelBinder
{
private const string CartSessionKey = "Cart";
public object BindModel(ControllerContext controllerContext, ModelBindingContext modelBindingContext)
{
Cart cart = null;
if(IsCartExistInSession(controllerContext))
{
cart = GetCartFromSession(controllerContext);
}
else
{
cart = new Cart();
AddCartToSession(controllerContext, cart);
}
return cart;
}
private static Cart GetCartFromSession(ControllerContext controllerContext)
{
return controllerContext.HttpContext.Session[CartSessionKey] as Cart;
}
private static void AddCartToSession(ControllerContext controllerContext, Cart cart)
{
controllerContext.HttpContext.Session[CartSessionKey] = cart;
}
private static bool IsCartExistInSession(ControllerContext controllerContext)
{
return controllerContext.HttpContext.Session[CartSessionKey] != null;
}
}
控制器
[HttpPost]
public ActionResult AddToCartfromAbout(Cart cart, int productId = 2)
{
var product = _productRepository.Products.First(p => p.ProductId == productId);
cart.AddItem(product, 1);
return View("About");
}
public ActionResult About()
{
// Need something here to get the value of cart
return View(cart);
}
【问题讨论】:
标签: asp.net-mvc-3 c#-4.0 asp.net-mvc-2 razor modelbinders