TryUpdateModel and unknown model-types

TryUpdateModel does not work on types not known at compile time. For example when creating an object through the Activator.CreateInstance()

To remedy this use this snippet of code:

public static class ControllerHelpers
{
  public static bool TryUpdateGenericModel(this Controller controller, object model)
  {
    var param = new Type[] { model.GetType() };
    var controllerType = controller.GetType();
    var controllerMethods = controllerType.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance);
    var TUMmethod = controllerMethods.First(x => x.Name.StartsWith("TryUpdateModel") && x.GetParameters().Count() == 1);
    var TUMgeneric = TUMmethod.MakeGenericMethod(param);
    var result = TUMgeneric.Invoke(controller, new object[] { model });
    return (bool)result;
  }
}

And in your controller when trying to update your model, use it like this:

var emptyModelObject = Activator.CreateInstance(modelType); // whichever way you get it doesn't really matter.
var result = this.TryUpdateGenericModel(modelObject);

Tags: , , ,

Leave a Reply