Skip to content

Instantly share code, notes, and snippets.

@juristr
Created February 19, 2013 10:07
Show Gist options
  • Save juristr/4984583 to your computer and use it in GitHub Desktop.
Save juristr/4984583 to your computer and use it in GitHub Desktop.
Model Binder for properly handling null values. See this post here for more details: http://juristr.com/blog/2012/02/aspnet-mvc3-doesnt-deserialize-nullable
public class ModelBinder : IModelBinder
{
private IModelBinder fallbackModelBinder;
public ModelBinder(IModelBinder fallbackModelBinder)
{
this.fallbackModelBinder = fallbackModelBinder;
}
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (controllerContext.HttpContext.Request.HttpMethod.Equals("GET", StringComparison.InvariantCultureIgnoreCase))
//|| controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
{
return this.fallbackModelBinder.BindModel(controllerContext, bindingContext);
}
else
{
if (controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
{
//ONLY do this for POST,PUT,DELETE requests that transmit application/json
string bodyText;
using (var stream = controllerContext.HttpContext.Request.InputStream)
{
stream.Seek(0, SeekOrigin.Begin);
using (var reader = new StreamReader(stream))
bodyText = reader.ReadToEnd();
}
if (string.IsNullOrEmpty(bodyText))
return (null);
return JsonConvert.DeserializeObject(bodyText, bindingContext.ModelType,
new[] { new IsoDateTimeToLocalTimeConverter() {
Culture = new System.Globalization.CultureInfo("de-DE"),
DateTimeStyles = System.Globalization.DateTimeStyles.AssumeUniversal
}});
}
else
{
return this.fallbackModelBinder.BindModel(controllerContext, bindingContext);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment