Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save chrisfcarroll/77cf7c939904f41a229edcf61a774426 to your computer and use it in GitHub Desktop.
Save chrisfcarroll/77cf7c939904f41a229edcf61a774426 to your computer and use it in GitHub Desktop.
To make stepping through the modelbinding process easier

Use the DebuggableModelBinder with a breakpoint to investigate what's happening when your complex model isn't binding as you expect.

Use the CheckBoxToBoolModelBinder to bind <input type="checkbox" > Note the Html standard describes "on" as the only valid postable value for a checkbox.. If you're posting something else, change the code. And don't that forget that unchecked means that nothing gets posted.

In either case, wire them up with e.g.:

public class MvcApplication : HttpApplication
{
    protected void Application_Start()
    {
        //
        // ...
        //
        ModelBinders.Binders.Add(typeof(bool), new CheckboxToBoolBinder());
        ModelBinders.Binders.Add(typeof(MyComplexTypeThatsHavingProblems), new DebuggableModelBinder());
    }
public class CheckboxToBoolBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (value != null)
{
if (value.AttemptedValue == "on" || value.AttemptedValue == "true" )
{
return true;
}
else
{
return false;
}
}
else
{
return base.BindModel(controllerContext, bindingContext);
}
}
}
public class DebuggableModelBinder : DefaultModelBinder
{
protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
{
if (propertyDescriptor.Name == "WhateverPropertyNameImHavingDifficultyWith")
{
var attemptedValue=bindingContext.ValueProvider.GetValue(propertyDescriptor.Name).AttemptedValue;
Console.WriteLine("Raw value : " + attemptedValue);
}
base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
}
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var result= base.BindModel(controllerContext, bindingContext);
return result;
}
protected override bool OnPropertyValidating(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value)
{
var result = base.OnPropertyValidating(controllerContext, bindingContext, propertyDescriptor, value);
if (!result)
{
Console.WriteLine("Here");
}
return result;
}
public static void Config(params Type[] types)
{
foreach (var type in types)
{
ModelBinders.Binders.Add(type, new DebuggableModelBinder());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment