我使用了在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 {};
}
}
答案 0 :(得分:2)
尝试使用以下逻辑:
if(controllerContext.RouteData.DataTokens["area"].ToString()=="yourArea")
{
//do something
}
答案 1 :(得分: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);
}
}