Custom binding of a polymorphic model does not bind properties of a derived type

Here is my custom middleware that is used to create the derived class.

public class LocationModalBinder : DefaultModelBinder { protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) { var type = bindingContext.ModelName + "." + "type"; Type typeToInstantiate; switch ((string) bindingContext.ValueProvider.GetValue(type).RawValue) { case "store": { typeToInstantiate = typeof (Store); break; } case "billing": { typeToInstantiate = typeof(LocationReference); break; } case "alternate": { typeToInstantiate = typeof(Address); break; } default: { throw new Exception("Unknown location identifier."); } } return base.CreateModel(controllerContext, bindingContext, typeToInstantiate); } } 

The problem is that it does not bind properties in a subtype. Only properties of the base type Location . Why is this?

+4
source share
2 answers

I think the call to return base.CreateModel beautiful as you tried.

I solved this by adding the following before the return base.CreateModel line:

 bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeToInstantiate); 
+1
source

Did it here ... fooobar.com/questions/124249 / ...

I don’t understand how many of the examples of this type of binder type worked without these assignments.

 public class LocationModalBinder : DefaultModelBinder { protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) { var type = bindingContext.ModelName + "." + "type"; Type typeToInstantiate; switch ((string) bindingContext.ValueProvider.GetValue(type).RawValue) { case "store": { typeToInstantiate = typeof (Store); break; } case "billing": { typeToInstantiate = typeof(LocationReference); break; } case "alternate": { typeToInstantiate = typeof(Address); break; } default: { throw new Exception("Unknown location identifier."); } } var model = Activator.CreateInstance(typeToInstantiate); bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeToInstantiate); bindingContext.ModelMetadata.Model = model; return model; } } 
0
source

Source: https://habr.com/ru/post/1495132/


All Articles