ASP.NET MVC Session Model Binder

  • 551
  • 0
  • 2015-08-05

摘要:ASP.NET MVC Session Model Binder

需求:把資料存放在 Session,方便跨 action(甚至 controller)存取相同資料,典型例子:購物車。

解法:http://www.codeproject.com/Articles/605595/ASP-NET-MVC-Custom-Model-Binder 、http://stackoverflow.com/questions/17618849/

// 宣告 資料類別
public class Cart
{
	private List itemList;

	public Cart()
	{
		this.itemList = new List();
	}
	//...
}

// 宣告 model binder
public class CartBinder : IModelBinder
{
	string cartSessionKey = "Cart";
	public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
	{
		var currentHttp = controllerContext.HttpContext;
		HttpRequestBase request = currentHttp.Request;

		Cart cart = (Cart)currentHttp.Session[cartSessionKey];
		if (cart == null)
		{
			cart = new Cart();
			currentHttp.Session[cartSessionKey] = cart;
		}

		return cart;
	}
}

// 在 Application_Start註冊
public class MvcApplication : System.Web.HttpApplication
{
	protected void Application_Start()
	{
		//...
		
		ModelBinders.Binders.Add(
			typeof(Cart), 
			new CartBinder()
		);
	}
}

// 在任意 action使用:直接當參數傳入,會自動從 session取值或初始化
public ActionResult MyAction(
	[ModelBinder(typeof(CartBinder))] Cart cartList, // 注意 Cart, CartBinder位置… 卡了一下
	string id, string filter = "1")
{
	// ...
}

public ActionResult MyOtherAction(
	Cart cartList, // 省略也是 ok的
	string id, string filter = "1")
{
	// ...
}