Send JSON object to MVC 6 WebApi controller using jQuery -


i'm having trouble sending json object mvc 6 webapi controller.

when @ raw data in fiddler, i'm sending, this:

username=brugernavn&password=adgangskode&documentid=document.dotx 

what think controller expecting recieve, this:

{"username":"brugernavn","password":"adgangskode","documentid":"document.dotx"} 

my controller code:

namespace demoapp.controllers {     [route("api/[controller]")]     public class documentcontroller : controller     {          // post: api/documentcontroller/getdocumentinformation         [httppost]         [route("[action]")]         public string getdocumentinformation([frombody] getdocumentinformationrequest documentinformationrequest)         if (documentinformationrequest == null)         {             return "null";         } else {             return "ok";         }     } } 

my getdocumentinformationrequest model class:

public class getdocumentinformationrequest {     public string username { get; set; }     public string password { get; set; }     public string documentid { get; set; } } 

my jquery code:

var source = {     'username': 'brugernavn',     'password': 'adgangskode',     'documentid': documentid } var apiurl = location.origin + "/api/documentcontroller/getdocumentinformation"; $.ajax({     type: "post",     datatype: "json",     url: apiurl,     data: source,     success: function (data) {         alert(data);     },     error: function (error) {         var x = error; //break here debugging.     } }); 

the ajax request hit controller, documentinformationrequest parameter null.

also ajax request ends in error-block every time, thats because controller returns "null" not valid json... (it return code 200, , no error thrown.)

i have tried many variations of ajax request, far none have resulted in sending json object controller correctly.

you need use json.stringify

$.ajax({    type: "post",    datatype: "json",    url: apiurl,    data: json.stringify(source),    success: function (data) {        alert(data);    },    error: function (error) {        var x = error; //break here debugging.    } }); 

Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -