StealthRT February 2016

Jquery AJAX sending JSON to web API 2 function

Hey all I am not sure why I am not able to send my data in json format to my web API 2 function.

My AJAX:

$('#btSubmit0').click(function () {
   $.ajax({
       url: "/febClassifieds/",
       type: "GET",
       crossDomain: true,
       contentType: 'application/json; charset=utf-8',
       dataType: "jsonp",
       data: JSON.stringify({ febID: "3a7c1773-128a-4b11-81f8-76302a678ddd" }),
       success: function (data) {
           console.log(data);
       },
       error: function (XMLHttpRequest, textStatus, errorThrown) {
           console.log('error: ', XMLHttpRequest);
       }
   });
});

My web API Function code:

[HttpGet]
[Route("febClassifieds/{febID}")]
public IHttpActionResult getFebClassifieds(febClassifieds.febClassifiedsVars data)
{
    try
    {
      ....code here......(never gets to this part anyways)
    }
}

The functions Class:

namespace WebApi.App.classes
{
    public class febClassifieds
    {
        public class febClassifiedsVars
        {
            public string febID { get; set; }
        }
    }
}

It never fires that function off when testing it out local. It just tells me the error of:

GET http://localhost:55473/febClassifieds?callback=jQuery17105937835655640811_1454958628992&{%22febID%22:%223a7c1773-128a-4b11-81f8-76302a678ddd%22}&_=1454958676643

In the console...

what could I possibly be missing in order to get this working?

Answers


Amir February 2016

Change type:"GET" with type:"POST" if you want to send JSON format.


M. Carlson February 2016

I would change your request type to POST in your ajax call and api endpoint.

Now move febClassifieds class to you're models folder (if you don't have one make one). Also change the namespace.

Then in your Controller change it to:

[HttpGet]
[Route("febClassifieds")]
public IHttpActionResult getFebClassifieds(febClassifieds.febClassifiedsVars data)
{

Also you might want to think about changing the structure of you febClassifieds class by removing the febClassifiedsVars class. The property febId is implicitly defined as a "variable" of the class it is defined in. By adding a nest class you are just adding unnecessary complexity, and a chance for errors.

Hope this helps!

Post Status

Asked in February 2016
Viewed 1,306 times
Voted 12
Answered 2 times

Search




Leave an answer