"how can i make a controller action take a dynamic parameter?" Code Answer

1

you could write a custom model binder which uses reflection and the typename parameter:

public class mymodelbinder : defaultmodelbinder
{
    protected override object createmodel(controllercontext controllercontext, modelbindingcontext bindingcontext, type modeltype)
    {
        var typevalue = bindingcontext.valueprovider.getvalue("typename");
        if (typevalue == null)
        {
            throw new exception("impossible to instantiate a model. the "typename" query string parameter was not provided.");
        }
        var type = type.gettype(
            (string)typevalue.convertto(typeof(string)),
            true
        );
        var model = activator.createinstance(type);
        bindingcontext.modelmetadata = modelmetadataproviders.current.getmetadatafortype(() => model, type);
        return model;
    }
}

and then simply:

[httppost]
public actionresult save([modelbinder(typeof(mymodelbinder))] object model) 
{
    context.entry(model).state = entitystate.modified;
    context.savechanges();
    return view();
}
By Rajesh Jr. on April 30 2022
Only authorized users can answer the Search term. Please sign in first, or register a free account.