Skip to content

Instantly share code, notes, and snippets.

@robertwilczynski
Created November 27, 2011 00:05
Show Gist options
  • Save robertwilczynski/1396558 to your computer and use it in GitHub Desktop.
Save robertwilczynski/1396558 to your computer and use it in GitHub Desktop.
Some fun with asp.net mvc dynamic model binder
protected void Application_Start()
{
ModelBinders.Binders.DefaultBinder = new DynamicModelBinder(ModelBinders.Binders.DefaultBinder);
}
public class DynamicModel : DynamicObject
{
readonly NameValueCollection _attributes;
public DynamicModel(NameValueCollection attributes)
{
_attributes = attributes;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = _attributes[binder.Name];
return true;
}
}
public class DynamicModelBinder : IModelBinder
{
readonly IModelBinder _defaultBinder;
public DynamicModelBinder(IModelBinder defaultBinder)
{
_defaultBinder = defaultBinder;
}
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (bindingContext.ModelType == typeof(object))
{
var form = controllerContext.HttpContext.Request.Form;
var model = new DynamicModel(form);
return model;
}
else
{
return _defaultBinder.BindModel(controllerContext, bindingContext);
}
}
}
Copy link

ghost commented Dec 2, 2013

DynamicModel how to use the controller? Can not seem to understand.

Copy link

ghost commented Dec 3, 2013

Maybe I did not put it quite right. I can not figure out how to cast the object to DynamicModel MyModel? Thanks in advance for your help.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment