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

デフォルトのモデル バインダーを呼び出したい場合は、インターフェイス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 に答える
2

次のロジックを使用してみてください。

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