0

I have an MVC controller with attribute and signature

[HttpPost] 
public void SubmitOrder(string id, string user, [FromBody]string data)

that has a custom route

routes.MapRoute(
    name: "Submit",
    url: "Order/{id}/{user}/Submit",
    defaults: new { controller = "Order", action = "SubmitOrder", id = "", user = "" }
);

Next, I have an AJAX post as:

$.ajax({
        type: "POST",
        url: baseUrl + "aaa/bbb/Submit",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(newData),
        success: function(response) {
            console.log(response);
});

I can reach SubmitOrder() where id = aaa and user = bbb have the proper values from the URL, but data is always null. I don't want to change the route, and want the JSON object to be in the request body (I know I can set an additional parameter in the route, but for design reasons I'd rather have it in the request body instead). However, I don't know how to access this data from the controller. Is there a way to read the request body without making changes to the route?

Booley
  • 819
  • 1
  • 9
  • 25

2 Answers2

1

In your ajax call, try

data: { data: json.stringify (newdata) }
Norbert Huurnink
  • 1,326
  • 10
  • 18
  • Thanks! Actually, this didn't work (the ajax call wouldn't even reach the endpoint at all, for some reason), but instead I moved the JSON.stringify() to the outside: `JSON.stringify({data: newData})` and that worked perfectly. – Booley Aug 16 '16 at 19:00
1

You can certainly do both.

Make sure you have the following header:

Content-Type: application/x-www-form-urlencoded

Your posted data is typically is a string formatted like this:

field=bletch&jackwagon=hungrypants

...but it doesn't have to be..

My guess is you are missing the header for form data: Content-Type: application/x-www-form-urlencoded

Check out this post

Reading FromUri and FromBody at the same time

Community
  • 1
  • 1
ListenFirst
  • 139
  • 4