【问题标题】:Custom Model Binder Which Will Only Work In One Area of MVC Application仅适用于 MVC 应用程序的一个领域的自定义模型绑定器
【发布时间】:2012-08-17 01:26:10
【问题描述】:

我使用了在 Global.asax 文件中配置的自定义模型绑定器。是否可以仅在应用程序的某些区域下使用此模型绑定器?

public class CreatorModelBinder : IModelBinder
{

    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        //what logic can i put here so that this only happens when the controller is in certain area- and when it's not in that area- then the default model binding would work
        var service = new MyService();
        if (System.Web.HttpContext.Current != null && service.IsLoggedIn)
            return service.Creator;
        return new Creator {};
    }
}

【问题讨论】:

    标签: asp.net-mvc-3 model-binding custom-model-binder


    【解决方案1】:

    如果您想调用默认模型绑定器,您应该从DefaultModelBinder 派生而不是直接实现IModelBinder 接口。

    然后:

    public class CreatorModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var area = controllerContext.RouteData.Values["area"] as string;
            if (string.Equals(area, "Admin"))
            {
                // we are in the Admin area => do custom stuff
                return someCustomObject;
            }
    
            // we are not in the Admin area => invoke the default model binder
            return base.BindModel(controllerContext, bindingContext);
        }
    }
    

    【讨论】:

      【解决方案2】:

      尝试使用以下逻辑:

      if(controllerContext.RouteData.DataTokens["area"].ToString()=="yourArea")
              {
                  //do something
              }
      

      【讨论】:

        猜你喜欢
        • 2017-12-05
        • 1970-01-01
        • 1970-01-01
        • 2010-10-17
        • 2018-10-27
        • 2019-02-26
        • 2015-11-10
        • 2015-11-29
        • 1970-01-01
        相关资源
        最近更新 更多