SeriousM
5/9/2014 - 7:40 AM

Custom C# ModelBinder

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";
	}
}