Created
November 27, 2011 00:05
-
-
Save robertwilczynski/1396558 to your computer and use it in GitHub Desktop.
Some fun with asp.net mvc dynamic model binder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
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
DynamicModel how to use the controller? Can not seem to understand.