public class ViewStateModelBinder : DefaultModelBinder
{
protected override object CreateModel(ControllerContext controllerContext,
ModelBindingContext bindingContext, Type modelType)
{
string modelName = bindingContext.ModelType.FullName;
ValueProviderResult clientObject =
bindingContext.ValueProvider.GetValue(modelName);
return clientObject == null
? base.CreateModel(controllerContext, bindingContext, modelType)
: ModelCompressor.Decompress(bindingContext.ModelType,
clientObject.AttemptedValue);
}
}
So instead of using some reflection call to create a object of my model type I create the base object using the compressed object. Sweet!
I learned you can do something like
ModelBinders.Binders.DefaultBinder = new ViewStateModelBinder ();
So this is pretty much a complete solution. Deploying it would involve adding the dll. Adding a line like the above setting the default model binder and then to use it all you need to do is write the Html helper line. I will probably make some HtmlHelper extension to make this look more special, but this was surprisingly easy and I think it is a powerful solution.
So if it is this easy to extend the model binding I would have to say that it is well engineered.
No comments:
Post a Comment