Skip to content

Custom view model binders

Alexanderius edited this page Jun 7, 2024 · 3 revisions

Custom view model binders

To use custom model view binder you should register it using HttpModelHandler.RegisterModelBinder, it will be added to binders pipeline, and register it in 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);

        ...
    }
}

Binder should be deriver from 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;

        // deserialization logic

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

    }
}

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

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

One example of custom model binder is JsonModelBinder.

<< Previous page Next page >>

Clone this wiki locally