代码之家  ›  专栏  ›  技术社区  ›  Damien

ASP.NETMVC:向控制器发送JSON

  •  10
  • Damien  · 技术社区  · 16 年前

    在ASP.NETMVC中向控制器发送帖子时,我希望能够发送JSON,而不是标准的查询字符串。我的前端工作正常(构建并提交JSON对象)。

    问题在于控制器端,MVC框架附带的默认ModelBinder不支持这一点。

    还有其他人遇到过这种情况吗?我的一个想法是,如果我可以简单地覆盖MVC如何处理FormCollection并在那里拦截,自己将值添加到集合中,并希望MVC能够以正常方式完成其余的工作。有人知道这是否可能吗?

    我认为,关键问题在于,我的问题不在于绑定,因为我的视图模型与以前的视图模型没有什么不同。问题是从JSON Post获取值。

    操作示例:

    public ActionResult MyFirstAction(Int32 ID, PersonObject Person, ClassObject ClassDetails)
    {
    //etc
    }
    

    1 回复  |  直到 16 年前
        1
  •  8
  •   Mike Valenty    16 年前

    我对json使用自定义模型绑定器,如下所示:

    public class JsonModelBinder<T> : 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<T>(json);
        }
    }
    

    然后将其连接到Global.asax.cs,如下所示:

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

    您可以在此处阅读更多关于此的信息: Inheritance is Evil: The Epic Fail of the DataAnnotationsModelBinder

    JsonModelBinder应仅用于类型为Product的控制器操作参数。Int32和ClassObject应该返回到DefaultModelBinder。您是否经历了不同的结果?