0

How can I post json object with inserted object? My code: Models code:

   public class MyModel
    {
        public string Text { set; get; }
        public int Param { set; get; }
        public InsertedModel insert { set; get; }
    }
public class InsertedModel
    {
        public string InsertedString { set; get; }
    }

JavaScript code:

<script>
    function createPost() {
        $.ajax({
            type: "POST", url: "/",
            success: function (data) { alert('data: ' + data); },
            data: { "Text": "Some Name", "Param": 30, "insert": { "InsertedString": "123" } },
            accept: 'application/json'
        });
    }

</script>

Controller code:

   [HttpPost]
    public void Index(Models.MyModel postReq)
    {
         //breakpoint
    }

In breakpoint i see:

Param: 30
Text: "Some Name"
insert: {Models\InsertedModel}
insert.InsertedString: null

Please help me. What I need to do with this? How can I see all my JSON struct in C# HTTPPost function?

1 Answer 1

2

You are just passing the object instead of JSON. Better convert this object to a string and specify the content type as JSON:

var requestData = JSON.stringify({ "Text": "Some Name", "Param": 30, "insert": { "InsertedString": "123" } });
function createPost() {
    $.ajax({
        type: "POST", url: "/",
        success: function (data) { alert('data: ' + data); },
        contentType: 'application/json',
        data: requestData,
        accept: 'application/json'
    });
}
Sign up to request clarification or add additional context in comments.

1 Comment

Perhaps just rename data to something else since he's expecting it in the success callback as well, so there might be some confusion - otherwise that's the correct answer +1

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.