Skip to content

Instantly share code, notes, and snippets.

@chilversc
Created November 13, 2014 17:34
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 chilversc/5466b2266d4a48e127e0 to your computer and use it in GitHub Desktop.
Save chilversc/5466b2266d4a48e127e0 to your computer and use it in GitHub Desktop.
Base class for custom model binder that binds a single text field to a single value
public abstract class SimpleModelBinderBase : IModelBinder
{
public object BindModel (ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var key = bindingContext.ModelName;
var result = bindingContext.ValueProvider.GetValue (key);
if (result == null) {
return null;
}
bindingContext.ModelState.SetModelValue (key, result);
var value = result.AttemptedValue;
if (string.IsNullOrWhiteSpace (value)) {
return null;
}
try {
return Parse (value);
} catch (Exception ex) {
bindingContext.ModelState.AddModelError (key, ex);
return null;
}
}
protected abstract object Parse (string value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment