asp.net-mvc - ASP.Net MVC : Sending JSON to Controller

标签 asp.net-mvc json model-binding

在 ASP.Net MVC 中向我的 Controller 发布帖子时,我希望能够发送 JSON 而不是标准 QueryStrings。我的前端工作正常(构建然后提交我的 JSON 对象)。

问题出在 Controller 端,MVC 框架附带的默认 ModelBinders 不支持这一点。

我已经看到了解决此问题的多种方法,其中之一是应用一个将对象作为参数的过滤器,使用 JSON 库对其进行反序列化,并将其添加到操作参数中。这并不理想。

另一种更好的方法是使用自定义模型绑定(bind)器。尽管我所看到的所有模型都假定您只有一个模型,并且这将是一个类而不是一个变量。如果你有多个,它会崩溃。

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

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

如果我是正确的,MVC 从 QueryString 中获取值并将其放入表单集合中,然后用于 ModelBinding。那么正确的方法不应该是改变 FormCollection 的分配方式吗?

Action 示例:

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

正常绑定(bind)有效,JSON 无效,模型绑定(bind)器的所有示例也无效。到目前为止,我最好的解决方案是将对象转换为字典并遍历每个参数并进行匹配。似乎不太理想。

最佳答案

我为 json 使用自定义模型绑定(bind)器,如下所示:

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 的 Controller 操作参数。 Int32 和 ClassObject 应该回退到 DefaultModelBinder。您是否遇到不同的结果?

关于asp.net-mvc - ASP.Net MVC : Sending JSON to Controller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2140845/

相关文章:

c# - 将内容放在 HttpResponseMessage 对象中?

javascript - 以 JSON 格式返回 HTML 并调用函数

c# - MySql.Data.MySqlClient.MySqlException - 已经有一个与此连接关联的打开的 DataReader,必须先将其关闭

C#反序列化Json数组不带[]

c# - 解析 json 响应为空

Asp.Net MVC 动态模型绑定(bind)前缀

php - Form::model 绑定(bind) Laravel 与 <select multiple>

c# - 为什么 ASP.NET Web Api 模型绑定(bind)使用参数类型来确定值的来源?

c# - 在 Entity Framework TPH 中映射子类值

c# - ASP.NET MVC 下拉列表不会填充结果