简体   繁体   中英

ASP.NET MVC Register custom Model Binder for all ViewModels

I have created a Custom Model Binder that works perfectly.

All my ViewModels extend the BaseViewModel however when I register the Model Binder for BaseViewModel it just doesn't run.

If I register every ViewModel "by hand" like the following line it works perfectly

ModelBinders.Binders[typeof(ArticlesViewModel)] =  new ContextDataBinder();

What I need to know if there is a way to do that kind of registration for all my viewModels without register all viewModels one by one .

As it was commented in my original post you can register all the model blinders by replacing the default binder

ModelBinders.Binders.DefaultBinder = new ContextDataBinder();

However that didn't worked for my specific case because the ViewModels that the framework creates automatically always return the previous ViewModel (in searches for example it doesn't return me filtered results but all the results).

I ended up creating a List of types containing the type of only the ViewModels that actually need to pass trough the ModelBinder and with a foreach e register them all one by one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM