Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I ended up using gt124's link <a href="http://lozanotek.com/blog/archive/2010/04/16/simple_json_model_binder.aspx" rel="noreferrer">model binder example</a> along with <a href="http://lostechies.com/jimmybogard/2009/03/18/a-better-model-binder/" rel="noreferrer">a better model binder</a> to write my own model binding logic. It ended up looking like this:</p> <pre><code>public interface IFilteredModelBinder : IModelBinder { bool IsMatch(Type modelType); } public class SmartModelBinder : DefaultModelBinder { private readonly IFilteredModelBinder[] _filteredModelBinders; public SmartModelBinder(IFilteredModelBinder[] filteredModelBinders) { _filteredModelBinders = filteredModelBinders; } public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { foreach (var filteredModelBinder in _filteredModelBinders) { if (filteredModelBinder.IsMatch(bindingContext.ModelType)) { return filteredModelBinder.BindModel(controllerContext, bindingContext); } } return base.BindModel(controllerContext, bindingContext); } } public class NewtonsoftJsonModelBinder : IFilteredModelBinder { public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase)) { // not JSON request return null; } var request = controllerContext.HttpContext.Request; request.InputStream.Position = 0; var incomingData = new StreamReader(request.InputStream).ReadToEnd(); if (String.IsNullOrEmpty(incomingData)) { // no JSON data return null; } object ret = JsonConvert.DeserializeObject(incomingData, bindingContext.ModelType); return ret; } public bool IsMatch(Type modelType) { var ret = (typeof(JsonModel).IsAssignableFrom(modelType)); return ret; } } </code></pre> <p>I then used JSON.net attributes to map to the different object properties (instead of DataContracts) on the models. The models all inherited from an empty base class JsonModel.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload