Booley Booley - 3 months ago 14
C# Question

How to read both from request URI and body in ASP.NET MVC controller and AJAX?

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?

Answer

In your ajax call, try

data: { data: json.stringify (newdata) }
Comments