Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a Controller Action take a dynamic parameter?

I would like to be able to post any serialized object to an action method and instantiate a new object of the posted type in order to use TryUpdateModel. They didn't teach me any of this stuff in the QBasic help file... How can I instantiate the unknown type based on the posted data?

If it would help, I could theoretically include the name of the type as a string in the posted data. I was hoping to avoid that because it seemed like I would need the full name of the type.

public void Save(object/dynamic whatever, string typename) {
    //Instantiate posted type
    //TryUpdateModel
    context.Entry(Thing).State = EntityState.Modified;
    context.SaveChanges();
}

Here is an example of a serialized object

Thing.Id=1&Thing.Name=blah&Thing.OptionID=1&Thing.ListItems.index=1&Thing.ListItems%5B1%5D.Id=1&Thing.ListItems%5B1%5D.Name=whatever&Thing.ListItems%5B1%5D.OptionID=2&Thing.ListItems%5B1%5D.ThingID=1&Thing.ListItems%5B1%5D.EntityState=16

From Fiddler

Thing.Id                            1
Thing.Name                          blah
Thing.OptionID                      1
Thing.ListItems.index               1
Thing.ListItems[1].Id               1
Thing.ListItems[1].Name             whatever
Thing.ListItems[1].OptionID         2
Thing.ListItems[1].ThingID          1
Thing.ListItems[1].EntityState      16
like image 663
Benjamin Avatar asked Jul 28 '11 15:07

Benjamin


1 Answers

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();
}
like image 89
Darin Dimitrov Avatar answered Oct 21 '22 09:10

Darin Dimitrov