ASP.Net MVC : Sending JSON to Controller

后端 未结 1 1336
星月不相逢
星月不相逢 2021-02-04 14:53

I want to be able to send JSON as opposed to the standard QueryStrings when making a post to my controllers in ASP.Net MVC. I have the Front-End stuff working fine (building and

1条回答
  •  情话喂你
    2021-02-04 15:50

    I use a custom model binder for json like this:

    public class JsonModelBinder : IModelBinder {
        private string key;
    
        public JsonModelBinder(string requestKey) {
            this.key = requestKey;
        }
    
        public object BindModel(ControllerContext controllerContext, ...) {
            var json = controllerContext.HttpContext.Request[key];
            return new JsonSerializer().Deserialize(json);
        }
    }
    

    And then wire it up in Global.asax.cs like this:

    ModelBinders.Binders.Add(
        typeof(Product),
        new JsonModelBinder("ProductJson"));
    

    You can read more about this here: Inheritance is Evil: The Epic Fail of the DataAnnotationsModelBinder

    EDIT

    The JsonModelBinder should be used on the controller action parameter typed as Product only. The Int32 and ClassObject should fall back to the DefaultModelBinder. Are you experiencing a different result?

    0 讨论(0)
提交回复
热议问题