1

On the HTML:

<div>
    <button onclick="clicker()">Click Me!</button>
</div>

<script type="text/javascript">
    function clicker() {
        var data = {
          id: 1,
          name: 'julius'
        };

        $.ajax({
            type: 'POST',
            url: '/api/test/',
            data: JSON.stringify(data),
            contentType: "application/json; charset=utf-8"
        });
    }
</script>

On the Controller:

public class TestController : ApiController
{
    public void Post([FromBody]string value)
    {
      Console.WriteLine();
    }
}

The value of the variable "value" on the controller is null, although, I pass data to ajax call. Can somebody please explain why this happens?

1 Answer 1

2

Instead of trying to receive the posted content as a string, create an object that encapsulates the properties you are posting:

public class Data
{
    public int id { get; set; }
    public string name { get; set; }
}

and then change your controller to:

public class TestController : ApiController
{
    public void Post(Data value)
    {
      int id = value.id;
      string name = value.name;
    }
}

If you really want to receive the posted data as a string this blog post by Darrel Miller might help:

Posting raw JSON to Web API.

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

1 Comment

Thanks Jon for sharing idea and the blog post! =)

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.