I want to use the UpdateModel method for the Sub Class, which was obtained at runtime, it would be great if someone could shed light on the fact that I am doing a full hash and / or regardless of m trying to make it possible.
I use the general action to validate partial view validation; I am trying to get away from a specific action for partial viewing.
Each partial view has a unique model, which is based on the base model:
public class ModelA : ModelBase{ [Required] public string SomeStringProperty{get;set;} ... } public class ModelB : ModelBase{ [Required] public DateTime? SomeDateProperty{get;set;} ... } public class ModelBase{ public Guid InstanceId{get;set;} }
I use FormCollection in action to get the submitted form elements and their values, this includes the type of model that View should use to validate its request. Ignore the security implications of this for this example, I know about them, and this is an internal proof of concept
[HttpPost] public ActionResult ChangeCaseState(int id, FormCollection formCollection) { Guid instanceId = new Guid(formCollection["instanceId"]); string modelType = formCollection["modelType"];
And here is the code that I use to return the Sub Class based on modelType passed to the controller.
private static ModelBase StateModelClassFactory(string stateModelTypeName, Guid instanceId) { switch (stateModelTypeName) { case "modelTypeA": return new ModelA(workflowInstanceId); case "modelTypeB": return new ModelB(workflowInstanceId); ... }
Since the return type of the StateModelClassFactory method belongs to the base class, although I actually return the Sub Class, the model binding used by the UpdateModel method only binds to the values ββin the base class.
Any ideas on how I can solve this problem?
UPDATE:
I created a client model binding:
public class CustomModelBinder : DefaultModelBinder { public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
And assigned a new model binding to the correct base class to see what happens next under the hood:
ModelBinders.Binders.Add(typeof(ModelBase), new CaseController.CustomModelBinder());
When I debug model binding and check the bindingContext, the Model property represents the correct Sub-class, but the ModelType property is a property of the base class. Should I look for a ModelType change in the BindModel method? If so, pointers to how to do this, the setter in ModelType seemed to be superfluous. I also noticed that SomeDateProperty from the Sub Class is actaully in the PropertyMetadata property .... It seems to be as close to behaving as we would like.