Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC model type conditional binding

I have an action:

[HttpPost]
public ActionResult(Animal a)
{

}

I'd like a to be a Rabbit or Dog depending on the incoming form data. Is there a simple way to achieve this?
Thank you

like image 409
LINQ2Vodka Avatar asked Feb 06 '26 15:02

LINQ2Vodka


1 Answers

In order to get this to work, you are looking at setting up your Action to accept a dynamic parameter, that a ModelBinder will convert to the appropriate type, either a Rabbit or Dog:

[HttpPost]
public ActionResult([ModelBinder(typeof(AnimalBinder))] dynamic a)
{

}

Since the Action doesn't know what the object is that it is getting, it needs a way of knowing what to convert that object to. You will need two things to achieve this. First, you have to embed in your View, EditorTemplate, whatever, what the model that you are binding to is:

@Html.Hidden("ModelType", Model.GetType())

Second, the model binder that will create an object of the appropriate type, based on the ModelType field you specified above:

public class AnimalBinder : DefaultModelBinder
    {
        protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
        {
            var typeValue = bindingContext.ValueProvider.GetValue("ModelType");
            var type = Type.GetType((string)typeValue.ConvertTo(typeof(string)), true);
            if (!typeof(Animal).IsAssignableFrom(type))
            {
                throw new InvalidOperationException("Bad Type");
            }
            var model = Activator.CreateInstance(type);
            bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, type);
            return model;
        }
    }

Once this is all in place, if you inspect the dynamic a object that is passed into the Action, you will see that it is of type Rabbit or Dog based on what the page model was.

like image 72
Pete Avatar answered Feb 09 '26 11:02

Pete



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!