3

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 }
            );

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

mmm interesting..i got it working too but looks like it's not working for multiple parameters. any way thanks for the answer
hello. check here encosia.com/using-jquery-to-post-frombody-parameters-to-web-api [FromBody] accepts Only one parameter per method
0

I wrote this simple code in JQuery to solve all my Microsoft .NET WebApi woes:

$.webApi = function (method, url, data) {
    return $.ajax(url, {
        type: method,
        data: typeof (data) === "object" ? JSON.stringify(data) : data,
        dataType: "json",
        contentType: "application/json"
    })
};

I call it like this:

$.webApi("POST", "http://url", {object:data});

Makes everything nice and simple. And I don't have to remember all the settings every time.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.