简体   繁体   English

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

[英]How to pass complex JSON object to ASP.net controller

I want to pass a complex JSON object. 我想传递一个复杂的JSON对象。 But when I debug the Controller Action all virtual Properties are null. 但是当我调试Controller Action时,所有虚拟属性都为null。 Working with ASP.NET, EF and CF. 使用ASP.NET,EF和CF.

JSON is send: 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
        }
    }
}

The Model trans: 模型转换:

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

    }
}

So when I always post the JSON via Fiddler all Virtual properties are null. 因此,当我总是通过Fiddler发布JSON时,所有虚拟属性都为空。

Debugsession

Before I worked with Foreign Keys as commented in the Model. 在使用模型中评论的外键之前。 That works fine. 这很好。

I want to rebuild the code to optimize the code itself. 我想重建代码以优化代码本身。

How can I initialize the Properties and deserialize the JSON correct? 如何初始化属性并反序列化JSON正确?

Regards Marcus 关心马库斯

I created a small working sample for you (please find below solution). 我为你创建了一个小样本(请找下面的解决方案)。 It mainly depends on how you construct your client side object. 它主要取决于您构建客户端对象的方式。

Model - 型号 -

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

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

Controller Actions - 控制器动作 -

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

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

Simple View - 简单视图 -

@{
    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>
}

When you run the page, it will hit the controller post action and check the below output - 当您运行该页面时,它将点击控制器发布操作并检查以下输出 -

在此输入图像描述

You're really close! 你真的很亲密! My answer depends on your name of your model parameter. 我的答案取决于您的模型参数的名称。

Lets say your action is as follows 让我们说你的行动如下

[HttpPost]
public ActionResult Test(trans model)
{

    return View();
}

Then your request body will be as follows 然后您的请求正文如下

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

Notice how the parameter name matches that of the JSON keys. 请注意参数名称如何与JSON键的名称匹配。

Hope this helps! 希望这可以帮助!

You can add [FromBody] inside the signature of your action : 您可以在动作的签名中添加[FromBody]

public ActionResult SomeAction([FromBody] trans trans)
{

    //Access trans here

}

solved. 解决了。 Send the Worng Json string. 发送Worng Json字符串。

The Correct JSON is: 正确的JSON是:

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

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

please compare with the JSON from my Question. 请与我的问题中的JSON进行比较。 As you see you doesen´t need to describe the model "trans" in the JSON. 如您所见,您不需要在JSON中描述模型“trans”。 Start your JSON Object from the Content od the model an deserialzer work. 从反序列化工作的模型的内容开始您的JSON对象。

Regards, Marcus Thanks ramiramilu your JSON String gives me the hint. 此致,Marcus感谢ramiramilu您的JSON字符串给了我提示。

From this post , You need to use json2.js to serialize your json object 这篇文章中 ,您需要使用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);
        }
    });

If this is not suitable for you, you may use the $.toDictionnary plugin specialy for submiting json objects collections. 如果这不适合您,您可以使用$ .toDictionnary插件专门提交 json对象集合。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将json作为对象传递给ASP.NET MVC控制器? - How to pass json as object to ASP.NET MVC controller? 如何使用POST将复杂对象从视图传递到控制器-ASP.NET MVC - How can i pass complex object from view to controller with POST - ASP.NET MVC 如何在ASP.NET MVC中返回复杂的Json对象 - How to return complex Json object in asp.net mvc javascript-如何将JSON对象中的数组从JavaScript传递给asp.net MVC控制器方法? - How to pass array in a JSON object from javascript to asp.net mvc controller method? 如何通过uri或http正文将复杂对象的实例传递给asp.net Web API控制器而没有任何参数? - How to pass instance of complex object via uri or http body without any params to asp.net web api controller? 如何使用Ajax和jQuery将复杂类型传递给ASP.NET MVC控制器 - How to Pass Complex Type to ASP.NET MVC Controller using Ajax and jQuery ASP.NET MVC-将复杂对象从视图返回到控制器 - ASP.NET MVC - Return complex object from view to controller 在ASP.NET MVC中使用重定向传递复杂对象? - Pass complex object with redirect in ASP.NET MVC? 如何使用JSON,jQuery向ASP.NET MVC Controller发布复杂对象数组? - How to post an array of complex objects with JSON, jQuery to ASP.NET MVC Controller? ASP.Net MVC:如何使用列表 ViewData object 或从 controller 传递到视图的其他复杂对象 - ASP.Net MVC: How to use a List ViewData object or other complex objects passed from a controller to a view
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM