Skip to content

Instantly share code, notes, and snippets.

@SeriousM
Created May 9, 2014 07:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SeriousM/9eea812832e225b7689a to your computer and use it in GitHub Desktop.
Save SeriousM/9eea812832e225b7689a to your computer and use it in GitHub Desktop.
Custom C# ModelBinder
// ...
protected void Application_Start()
{
ModelBinders.Binders.Add(typeof(bool), new OnOffModelBinder());
ModelBinders.Binders.Add(typeof(bool?), new OnOffModelBinder());
}
// ...
using System.Web.Mvc;
/// <summary>
/// This model binder converts the value "on" to true.
/// It's necessary for form-checkboxes (bootstrap) that sends "on" instead a boolean value
/// </summary>
public class OnOffModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (bindingContext.ModelType == typeof(bool?))
{
if (string.IsNullOrEmpty(valueProviderResult.AttemptedValue))
{
return null;
}
}
return (valueProviderResult.AttemptedValue ?? string.Empty).ToLower() == "on";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment