Skip to content

Custom view model binders

Alexanderius edited this page Jul 3, 2025 · 6 revisions

Custom view model binders

To use a custom view model binder, you should register it using HttpModelHandler.RegisterModelBinder. It will be added to the binders pipeline, and you should also register it in the IOC container: DIContainer.Current.Register<MyModelBinder>.

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        ...

        HttpModelHandler.RegisterModelBinder<MyModelBinder>();

        app.UseSimplifyWeb();
    }

    public void ConfigureServices(IServiceCollection services)
    {
        ...

        DIContainer.Current.Register<MyModelBinder>(LifetimeType.Singleton);

        ...
    }
}

A binder should be derived from the IModelBinder interface.

public class MyModelBinder : IModelBinder
{
    public Task BindAsync<T>(ModelBinderEventArgs<T> args)
    {
        // Checking binder applicability
        if (args.Context.Request.ContentType == null || !args.Context.Request.ContentType.Contains("required mime type"))
            return Task.CompletedTask;

        // Deserialization logic
        args.SetModel(/* set deserialized model here to use by controllers */);

        return Task.CompletedTask;
    }
}

If you want to use your binder without the default binders, you should clear the binders list first.

HttpModelHandler.ModelBindersTypes.Clear();
HttpModelHandler.RegisterModelBinder<MyModelBinder>();

One example of a custom model binder is JsonModelBinder.

<< Previous page Next page >>

Clone this wiki locally