2

I'm trying to do a POST request of a json object and convert it into a class but it's not working. Here's the JS that's sending the object:

var TheAjaxData = { 'Property1': 'TheValue1', 'Property2': 'TheValue2', 'Property3': 'TheValue3' } $.ajax({ url: "/thewebapi/themethod", type: "POST", data: TheAjaxData, contentType: 'application/json; charset=utf-8', success: function (msg, textStatus, request) { console.log(msg); } }); 

The WebAPI receives the request so I know the routing is correct but TheObject is null. This is the code:

[RoutePrefix("thewebapi")] public class TheWebAPIController : ApiController { [Route("themethod")] public HttpResponseMessage Post([FromBody] TheRequestObjectModel TheObject) { var testvalue = TheObject.Property1; } public class TheRequestObjectModel { public string Property1 { get; set; } public string Property2 { get; set; } public string Property3 { get; set; } } } 

This needs to work with a POST, not a GET. I'm pretty sure I'm close but it's not working. What do I need to change to get the object I'm sending converted into TheRequestObjectModel?

1
  • 1
    you need to stringify the payload data: JSON.stringify(TheAjaxData) Commented Dec 26, 2017 at 13:10

2 Answers 2

2

Try to convert your js object into json (as json formats your data in an object):

var TheAjaxData = { 'Property1': 'TheValue1', 'Property2': 'TheValue2', 'Property3': 'TheValue3' } $.ajax({ url: "/thewebapi/themethod", type: "POST", data: JSON.stringify(TheAjaxData), contentType: 'application/json; charset=utf-8', success: function (msg, textStatus, request) { console.log(msg); } }); 
Sign up to request clarification or add additional context in comments.

Comments

1

If you want to decorate the API action with [FromBody], you should serialize to Json when posting the data from client side. You can use JSON.stringify(TheAjaxData).

$.ajax({ url: "/thewebapi/themethod", type: "POST", data: JSON.stringify(TheAjaxData), contentType: 'application/json; charset=utf-8', success: function (msg, textStatus, request) { console.log(msg); } }); 

Another option is removing the [FromBody] attribute and pass the javascript object directly. Actually, in your case TheRequestObjectModel just have string properties and it doesn't contain another complex object. So, It could be better to remove the [FromBody] attribute.

[Route("themethod")] public HttpResponseMessage Post(TheRequestObjectModel TheObject) { var testvalue = TheObject.Property1; } $.ajax({ url: "/thewebapi/themethod", type: "POST", data: TheAjaxData, contentType: 'application/json; charset=utf-8', success: function (msg, textStatus, request) { console.log(msg); } }); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.