8

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.

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?

Regards Marcus

5 Answers 5

14

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 -

enter image description here

Sign up to request clarification or add additional context in comments.

4 Comments

Can you give me the Json String your script generates?
{"tID":123,"Location":{"locID":456}}
@ramiramilu , here you are binding the form values to javascript object and then converting them to json using Json.stringigy. var o = new Object(); o.tID = 123; o.Location = new Object(); o.Location.locID = 456; Is there any alternate so that i don't have to bind these values one by one. Since i have a very complex and large form which consist of large no of dynamic generated elements , and i need to post them to controller.
@ramiramilu Thanks, it works as i wanted , i don't know if its the best option but i am using it since on posting it passes values to controller in a strongly type model , so i am happy
2

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.

Hope this helps!

2 Comments

i tested you´re solution and rename the JSON key "Location" to "trans.Location" but there is no change in the debug session
My answer is definitely correct as I've even tested it in a sample app. You only needed to change the "model" to reflect your argument name. If you don't understand what this means then give me you action code and I'll update my answer to reflect it.
1

You can add [FromBody] inside the signature of your action :

public ActionResult SomeAction([FromBody] trans trans)
{

    //Access trans here

}

1 Comment

No effect, the Propertie is null
1

solved. Send the Worng Json string.

The Correct JSON is:

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. As you see you doesen´t need to describe the model "trans" in the JSON. Start your JSON Object from the Content od the model an deserialzer work.

Regards, Marcus Thanks ramiramilu your JSON String gives me the hint.

Comments

0

From this post, You need to use json2.js to serialize your json object

  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.

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

1 Comment

i dont get an idea how that helps to solve my problem, can you give me another hint?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.