Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/opengl/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将复杂的JSON对象传递给ASP.net控制器_C#_Asp.net_Json_Asp.net Mvc_Entity Framework - Fatal编程技术网

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

C# 如何将复杂的JSON对象传递给ASP.net控制器,c#,asp.net,json,asp.net-mvc,entity-framework,C#,Asp.net,Json,Asp.net Mvc,Entity Framework,我想传递一个复杂的JSON对象。但当我调试控制器操作时,所有虚拟属性都为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 { "tr

我想传递一个复杂的JSON对象。但当我调试控制器操作时,所有虚拟属性都为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时,所有虚拟属性都为null

在使用外键之前,如模型中所述。那很好

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

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

问候
Marcus

我为您创建了一个小的工作示例(请找到下面的解决方案)。这主要取决于如何构造客户端对象

型号-

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>
}
简单视图-

 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>
}
@{
ViewBag.Title=“主页”;
}   
@节脚本{
$(函数(){
var o=新对象();
o、 tID=123;
o、 位置=新对象();
o、 Location.locID=456;
$.ajax({
url:'@url.Action(“提交”、“主页”),
类型:“POST”,
cache:false,
数据:JSON.stringify({trans:o}),
contentType:“应用程序/json;字符集=utf-8”,
成功:功能(数据){
如果(数据){
警惕(“成功”);
}
},
错误:函数(jqXhr、textStatus、errorshown){
警报(错误抛出);
}
});
})
}
运行页面时,它将点击控制器post操作并检查以下输出-


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

public ActionResult SomeAction([FromBody] trans trans)
{

    //Access trans here

}

你真的很接近!我的答案取决于模型参数的名称

假设你的行动如下

[HttpPost]
public ActionResult Test(trans model)
{

    return View();
}
{
   "model.tID":3,
   "model.Location":{
      "locID":2
   }
}
那么您的请求主体将如下所示

[HttpPost]
public ActionResult Test(trans model)
{

    return View();
}
{
   "model.tID":3,
   "model.Location":{
      "locID":2
   }
}
请注意参数名如何匹配JSON键的名称

希望这有帮助

From,您需要使用来序列化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);
        }
    });
如果这不适合您,您可以专门使用插件来提交json对象集合

  var trans={'trans':{...}};//trans
   $.ajax({
       url: "api/trans",
       type: "POST",
       data: $.toDictionary(trans),
       ...
      });
解决了。 发送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字符串给了我提示。

你能给我你的脚本生成的JSON字符串吗?
{“tID”:123,“Location”:{“locID”:456}
@ramiramilu,这里你将表单值绑定到javascript对象,然后使用JSON.stringy将它们转换成JSON。var o=新对象();o、 tID=123;o、 位置=新对象();o、 Location.locID=456;是否有其他方法,以便我不必逐个绑定这些值。由于我有一个非常复杂和庞大的表单,其中包含大量动态生成的元素,我需要将它们发布到controller。@Ramilu谢谢,它可以按照我的要求工作,我不知道这是否是最好的选择,但我正在使用它,因为在发布时,它会以强类型模型将值传递给controller,所以我很高兴我测试了Your’s解决方案,并将JSON键“Location”重命名为“trans.Location”,但调试会话中没有任何更改。我的回答肯定是正确的,因为我甚至在一个示例应用程序中对它进行了测试。您只需更改“模型”以反映您的参数名称。如果你不明白这意味着什么,那么给我你的行动代码,我会更新我的答案来反映它。没有效果,属性为空。我不知道如何帮助解决我的问题,你能给我另一个提示吗?