2

我使用了在 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 {};
    }
}
4

2 回答 2

2

尝试使用以下逻辑:

if(controllerContext.RouteData.DataTokens["area"].ToString()=="yourArea")
        {
            //do something
        }
于 2012-08-16T17:20:54.370 回答
2

如果你想调用默认的模型绑定器,你应该派生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);
    }
}
于 2012-08-16T17:26:10.473 回答