Mar*_*cus 8 c# asp.net asp.net-mvc json 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
}
}
}
Run Code Online (Sandbox Code Playgroud)
模型转换:
public class trans
{
[Key]
public int tID { get; set; }
//public int? locID { get; set; }
public virtual Location Location { get; set; }
}
}
Run Code Online (Sandbox Code Playgroud)
因此,当我总是通过Fiddler发布JSON时,所有虚拟属性都为空.

在使用模型中评论的外键之前.这很好.
我想重建代码以优化代码本身.
如何初始化属性并反序列化JSON正确?
关心马库斯
ram*_*ilu 12
我为你创建了一个小样本(请找下面的解决方案).它主要取决于您构建客户端对象的方式.
型号 -
public class trans
{
[Key]
public int tID { get; set; }
public virtual Location Location { get; set; }
}
public class Location
{
public int locID { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
控制器动作 -
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult Submit(trans trans)
{
return null;
}
Run Code Online (Sandbox Code Playgroud)
简单视图 -
@{
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>
}
Run Code Online (Sandbox Code Playgroud)
当您运行该页面时,它将点击控制器发布操作并检查以下输出 -

| 归档时间: |
|
| 查看次数: |
10820 次 |
| 最近记录: |