So I have a custom generic model binder, that handle both T and Nullable<T>.
But I automatically create the bindigs via reflection. I search trhough the entire appdomain for enumeration flagged with specific attribute and I want to bind theese enums like this:
AppDomain
.CurrentDomain
.GetAssemblies()
.SelectMany(asm => asm.GetTypes())
.Where(
t =>
t.IsEnum &&
t.IsDefined(commandAttributeType, true) &&
!ModelBinders.Binders.ContainsKey(t))
.ToList()
.ForEach(t =>
{
ModelBinders.Binders.Add(t, new CommandModelBinder(t));
//the nullable version should go here
});
But here is the catch. I can't bind the Nullable<T> to CommandModelBinder.
I'm thinking the runtime code generation, but I never do this, and maybe there is other options on the market. Any idea to achieve this?
Thanks,
Péter
If you've got T
, you can create Nullable<T>
using Type.MakeGenericType
:
ModelBinders.Binders.Add(t, new CommandModelBinder(t));
var n = typeof(Nullable<>).MakeGenericType(t);
ModelBinders.Binders.Add(n, new CommandModelBinder(n));
I don't know how your CommandModelBinder
works and what the appropriate constructor argument is, you may need
ModelBinders.Binders.Add(n, new CommandModelBinder(t));
instead.
Note: MakeGenericType
will throw an exception if called with the wrong type. I haven't added error checking, since you're already filtering to only get the types for which this makes sense. Keep this in mind if you change your filtering though.
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.