How can I invoke a custom model binder in MVC4?

后端 未结 1 1878
花落未央
花落未央 2021-01-03 03:42

So it seems like several people (like here and here) have had issues with MVC4 model binding for ApiControllers, but none of them seem to quite address the

相关标签:
1条回答
  • 2021-01-03 04:08

    If you're talking ApiControllers, then you're trying to model bind in Web API and now MVC Here's a sample model binder

      public class MyRequestModelBinderProvider : ModelBinderProvider
        {
            MyRequestModelBinder binder = new MyRequestModelBinder();
            public IdeaModelBinderProvider()
            {          
            }
    
            public override IModelBinder GetBinder(HttpActionContext actionContext, ModelBindingContext bindingContext)
            {
                if (bindingContext.ModelType == typeof(MyRequestModel))
                {
                    return binder;
                }
    
                return null;
            }
        } 
    

    Here's an example of registering a custom model binder provider

     IEnumerable<object> modelBinderProviderServices = GlobalConfiguration.Configuration.ServiceResolver.GetServices(typeof(ModelBinderProvider));
     List<Object> services = new List<object>(modelBinderProviderServices);
     services.Add(new MyRequestModelBinderProvider());
     GlobalConfiguration.Configuration.ServiceResolver.SetServices(typeof(ModelBinderProvider), services.ToArray());
    

    Now in your custom model binder you use the contexts to access the querystring values

      public class MyRequestModelBinder :  IModelBinder
        {
            public MyRequestModelBinder()
            {
    
            }
    
            public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
            {
                MyRequestModel yourModel; 
                //use contexts to access query string values
                //create / update your model properties
    
                bindingContext.Model = yourModel;  
                //return true || false if binding is successful
            }
    

    Make sure your using the classes and interfaces for WebAPI and not MVC. Some of the names are the same, but different namespaces and dlls

    0 讨论(0)
提交回复
热议问题