25

我需要知道如何IModelBinder在 MVC 4 中创建自定义,并且它已被更改。

必须实施的新方法是:

bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext);
4

4 回答 4

28

有 2 个 IModelBinder 接口:

  1. System.Web.Mvc.IModelBinder这与以前的版本相同,没有改变
  2. System.Web.Http.ModelBinding.IModelBinderWeb API 和 ApiController 使用它。所以基本上在这个方法中,你必须将 设置actionContext.ActionArguments为相应的值。您不再返回模型实例。
于 2012-03-28T15:11:49.617 回答
24

This link, provided by Steve, provides a complete answer. I'm adding it here for reference. Credit goes to dravva on asp.net forums.

First, create a class derived from IModelBinder. As Darin says, be sure to use the System.Web.Http.ModelBinding namespace and not the familiar MVC equivalent.

public class CustomModelBinder : IModelBinder
{
    public CustomModelBinder()
    {
        //Console.WriteLine("In CustomModelBinder ctr");
    }

    public bool BindModel(
        HttpActionContext actionContext, 
        ModelBindingContext bindingContext)
    {
        //Console.WriteLine("In BindModel");
        bindingContext.Model = new User() { Id = 2, Name = "foo" };
        return true;
    }
}

Next, provide a provider, which acts as a factory for your new binder, and any other binders you may add in the future.

public class CustomModelBinderProvider : ModelBinderProvider
{
    CustomModelBinder cmb = new CustomModelBinder();
    public CustomModelBinderProvider()
    {
        //Console.WriteLine("In CustomModelBinderProvider ctr");
    }

    public override IModelBinder GetBinder(
        HttpActionContext actionContext,
        ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelType == typeof(User))
        {
            return cmb;
        }

        return null;
    }
}

Finally, include the following in your Global.asax.cs (e.g., Application_Start).

var configuration = GlobalConfiguration.Configuration;

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

Now, you can just delare the new type as a parameter to your action methods.

public HttpResponseMessage<Contact> Get([ModelBinder(typeof(CustomModelBinderProvider))] User user)

or even

public HttpResponseMessage<Contact> Get(User user)
于 2012-04-13T19:58:22.133 回答
8

在没有 ModelBinderProvider 的情况下添加模型绑定器的一种更简单的方法是:

GlobalConfiguration.Configuration.BindParameter(typeof(User), new CustomModelBinder());
于 2013-02-13T14:48:25.567 回答
3

Todd 帖子的 RC 更新:

添加模型绑定器提供程序已简化:

var configuration = GlobalConfiguration.Configuration;

configuration.Services.Add(typeof(ModelBinderProvider), new YourModelBinderProvider());
于 2012-09-13T12:13:32.183 回答