ASP.NET MVC: Action Filter to set up controller variables?

后端 未结 3 1689
终归单人心
终归单人心 2021-02-04 06:43

I have a scenario whereby with every page request I must check the session of the presence of a particular ID. If this is found I must grab a related object from the database an

3条回答
  •  迷失自我
    2021-02-04 06:57

    Another way is to do that with Model Binders. Suppose that object is ShoppingCart

    //Custom Model Binder
    public class ShoppingCarModelBinder : IModelBinder
        {
            public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
            {
                //TODO: retrieve model or return null;
            }
        }
     //register that binder in global.asax in application start
    
    ModelBinders.Binders.Add(typeof(ShoppingCart), new ShoppingCartBinder());
    
    // controller action
    
    public ActionResult DoStuff(ShoppingCart cart)
    {
         if(cart == null)
         {
         //whatever you do when cart is null, redirect. etc
         }
         else
         {
         // do stuff with cart
         }
    }
    

    Moreover, this is more unit testable and clear way, as this way action relies on parameters supplied from outside

提交回复
热议问题