Domanda

I've used custom model binders which are configured in the Global.asax file. Is it possible to only use this model binder under certain areas of the application?

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 {};
    }
}
È stato utile?

Soluzione

If you want to invoke the default model binder you should derive from DefaultModelBinder instead of directly implementing the IModelBinder interface.

And then:

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);
    }
}

Altri suggerimenti

Try to use the following logic:

if(controllerContext.RouteData.DataTokens["area"].ToString()=="yourArea")
        {
            //do something
        }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top