Created
November 13, 2014 17:34
-
-
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
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
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