Created
May 9, 2014 07:40
-
-
Save SeriousM/9eea812832e225b7689a to your computer and use it in GitHub Desktop.
Custom C# ModelBinder
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.Add(typeof(bool), new OnOffModelBinder()); | |
ModelBinders.Binders.Add(typeof(bool?), new OnOffModelBinder()); | |
} | |
// ... |
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
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