Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameters null in Web API ajax Call

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 }
            );
like image 838
chamara Avatar asked Feb 04 '26 09:02

chamara


1 Answers

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.

like image 159
Jason P Avatar answered Feb 06 '26 23:02

Jason P



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!