This is the first time i'm working with Web API. i'm trying to call a web api through a jquery ajax call. ajax call hits the web api action successfully but the string parameter "xx" is always null.
Ajax call
var x = "chamara";
$.ajax({
type: 'POST',
url: 'http://localhost:1557/api/values/mytest',
data: '{"xx":"' + x + '"}',
dataType: 'json',
});
Web Api action.
[AcceptVerbs("GET", "POST")]
public void mytest([FromBody]string xx)
{
string a = xx;
}
web api routes configuration.
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { action = "get", id = RouteParameter.Optional }
);
Try this:
var x = "chamara";
$.ajax({
type: 'POST',
url: 'http://localhost:1557/api/values/mytest',
data: { '' : x },
dataType: 'json',
});
I encountered the same thing this morning. I'm not sure why and I feel like there should be a better way, but it worked for me.
Alternatively, see this SO question where the solutions suggest setting the contentType to application/json.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With