Custom model binding is not called when the type is NULL

I have a custom structure called TimeOfDay , which is used in the view model as follows:

 public class MyViewModel { public TimeOfDay TimeOfDay { get; set; } } 

I created a custom TimeOfDayModelBinder called TimeOfDayModelBinder and registered it in Global.asax.cs as follows:

 ModelBinders.Binders.Add(typeof(TimeOfDay), new TimeOfDayModelBinder()); 

And everything works fine. However, if I change my look at this model:

 public class MyViewModel { public TimeOfDay? TimeOfDay { get; set; } // Now nullable! } 

My custom mediator is no longer called. I know that the property is no longer a TimeOfDay type, but Nullable is different. Does this mean that I have to add my own model binding twice to Global.asax.cs as follows:

 ModelBinders.Binders.Add(typeof(TimeOfDay), new TimeOfDayModelBinder()); ModelBinders.Binders.Add(typeof(TimeOfDay?), new TimeOfDayModelBinder()); 

It works, but I just don't like it. Is this really necessary in order to treat my type as nullable, or is there something I am missing?

+7
source share
2 answers

In @LukeH's comment, this seems to be necessary. I think this also makes sense, since TimeOfDay and Nullable<TimeOfDay> are really two different types in the CLR. So I think I need to live with this. :-)

+1
source

In fact, this is not the answer to your question, but an alternative solution. Maybe better ...

In MVC3, you can create an IModelBinderProvider. The implementation will be something like this:

 public class TimeOfDayModelBinderProvider : IModelBinderProvider { public IModelBinder GetBinder(Type modelType) { if(modelType == typeof(TimeOfDay) || modelType == typeof(TimeOfDay?)) { return new TimeOfDayModelBinder(); } return null; } } 

You need to register it in the DependencyResolver / IOC container or do it (at the launch of the Global.asax application):

 ModelBinderProviders.BinderProviders.Add(new TimeOfDayModelBinderProvider()); 
+7
source

All Articles