jquery - WebGet JSON complex parameter -
the service method looks this
public class uploaditem { public string filename { get; set; } public string filedesc { get; set; } } [operationcontract, webget] public int writeuploaditem(uploaditem uploaditem) { //implementation } the invocation looks this
var data = { filename: self.filename(), filedesc: self.filedesc(), }; $.ajax({ url: "fx.svc/writeuploaditem", data: { uploaditem: data }, success: function (result) { //implementation }, error: function (result) { alert($.parsejson(result.responsetext).message); } }); which produces
get http://localhost:49701/fx.svc/writeuploaditem?uploaditem%5bfilename%5d =2014-01-21.gif&uploaditem%5bfiledesc%5d=adesgfa http/1.1 x-requested-with: xmlhttprequest accept: */* referer: http://localhost:49701/index.html#upload-queue accept-language: en-au,en;q=0.5 accept-encoding: gzip, deflate user-agent: mozilla/5.0 (windows nt 6.3; wow64; trident/7.0; rv:11.0) gecko host: localhost:49701 dnt: 1 connection: keep-alive those url encoded parameters when decoded
uploaditem[filename]=2014-01-21.gif&uploaditem[filedesc]=adesgfa the webget method invoked parameter null.
i'm passing single parameter method
var userid = "73c2e254-5440-45eb-9099-58fa08dd037b"; // me.userid(); $.ajax({ url: "fx.svc/userfiles", data: { userid: userid }, success: function (result) { //implementation }, error: function (result) { alert($.parsejson(result.responsetext).message); } }); as far can see, difference value of parameter different. there lot more fields removed more troublesome data types , intrigued discover problem occurs simple strings.
what's wrong , should it? there sort of attribute need put on c# uploaditem class?
the default encoding used $.ajax() application/x-www-form-urlencoded.
to fix this, control encoding , tell other end encoding used. note explicit stringification of object, , explicit encoding of text/json contenttype.
var data = { filename: self.filename(), filedesc: self.filedesc(), }; $.ajax({ url: "fx.svc/writeuploaditem", data: json.stringify(data), contenttype: "text/json" }).done(function (result) { //implementation }).error(function (err) { //handle error }); the content type encoding specify used return value unless specify different encoding. it's satisfactory json since $.ajax() magically parse result object, when returning simple type such int, you'll need specify return encoding of text/plain using datatype parameter.
$.ajax({ url: "fx.svc/writeuploaditem", data: json.stringify(data), contenttype: "text/json", datatype: "text/plain" }).done(function (result) { //implementation }).error(function (err) { //handle error });
Comments
Post a Comment