如何将复杂的JSON对象传递给ASP.net控制器

时间:2015-05-13 12:42:35

标签: c# asp.net json asp.net-mvc entity-framework

我想传递一个复杂的JSON对象。但是当我调试Controller Action时,所有虚拟属性都为null。使用ASP.NET,EF和CF。

JSON发送:

    POST http://localhost:53214/api/trans/ HTTP/1.1
    Pragma: no-cache
    Content-Type: application/json; charset=utf-8
    Host: localhost:53214
    Content-Length: 221

{
    "trans": {
        "Location": {
            "locID": 2
        }
    }
}

模型trans:

    public class trans
    {
        [Key]
        public int tID { get; set; }
        //public int? locID { get; set; }
        public virtual Location Location { get; set; }

    }
}

因此,当我总是通过Fiddler发布JSON时,所有虚拟属性都为空。

Debugsession

在使用模型中评论的外键之前。这很好。

我想重建代码以优化代码本身。

如何初始化属性并反序列化JSON正确?

此致 马库斯

5 个答案:

答案 0 :(得分:11)

我为你创建了一个小样本(请找下面的解决方案)。它主要取决于您构建客户端对象的方式。

型号

public class trans
{
    [Key]
    public int tID { get; set; }
    public virtual Location Location { get; set; }
}

public class Location
{
    public int locID { get; set; }
} 

控制器操作 -

 public ActionResult Index()
 {
      return View();
 }

 [HttpPost]
 public JsonResult Submit(trans trans)
 {
      return null;
 }

简单视图 -

@{
    ViewBag.Title = "Home Page";
}   

<table id="example" class="display">
</table>

@section scripts{
    <script>
        $(function() {
            var o = new Object();
            o.tID = 123;
            o.Location = new Object();
            o.Location.locID = 456;

            $.ajax({
                url: '@Url.Action("Submit", "Home")',
                type: "POST",
                cache: false,
                data: JSON.stringify({ trans : o }),
                contentType: "application/json; charset=utf-8",
                success: function(data) {
                    if (data) {
                        alert("Success");
                    }
                },
                error: function(jqXhr, textStatus, errorThrown) {
                    alert(errorThrown);
                }
            });
        })
    </script>
}

当您运行该页面时,它将点击控制器发布操作并检查以下输出 -

enter image description here

答案 1 :(得分:1)

你真的很亲密!我的答案取决于您的模型参数的名称。

让我们说你的行动如下

[HttpPost]
public ActionResult Test(trans model)
{

    return View();
}

然后您的请求正文如下

{
   "model.tID":3,
   "model.Location":{
      "locID":2
   }
}

注意参数名称如何与JSON键的名称相匹配。

希望这有帮助!

答案 2 :(得分:0)

您可以在操作的签名中添加[FromBody]

public ActionResult SomeAction([FromBody] trans trans)
{

    //Access trans here

}

答案 3 :(得分:0)

解决。 发送Worng Json字符串。

正确的JSON是:

Pragma: no-cache
Content-Type: application/json; charset=utf-8
Host: localhost:53214
Content-Length: 144

{
    "Location": {
        "locID": 2
    }
}

请与我的问题中的JSON进行比较。如您所见,您不需要在JSON中描述模型“trans”。从反序列化器的模型内容开始您的JSON对象。

此致 马库斯 谢谢ramiramilu你的JSON字符串给了我提示。

答案 4 :(得分:-1)

this post开始,您需要使用json2.js来序列化您的json对象

  var json = JSON.stringify({'trans':{...}});

    $.ajax({
        url: '/api/trans',
        type: 'POST',
        dataType: 'json',
        data: json,
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            $("#target").html(data);
        }
    });

如果这不适合您,您可以使用$.toDictionnary插件专门提交json对象集合。

  var trans={'trans':{...}};//trans
   $.ajax({
       url: "api/trans",
       type: "POST",
       data: $.toDictionary(trans),
       ...
      });
相关问题