I want to pass a complex JSON object. But when I debug the Controller Action all virtual Properties are null. Working with ASP.NET, EF and CF.
JSON is send:
    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.

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?
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 -

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With