javascript - How do you send a complex object with an ajax post method to c# controller? -


i'm trying send complex javascript object mvc controller post method. receive badrequest response every time run method. won't let me debug visual studio, web developer tools. checked fiddler see json object seems in same order view model. please me this? using asp.net core 1.0. please let me know if need provide more information.

here's view model:

public class routeviewmodel     {         public routeviewmodel() { }         public list<checkpointviewmodel> checkpoints { get; set; }         public int totaldistance { get; set; }     }   public class checkpointviewmodel     {         public decimal latitude { get; set; }         public decimal longitude { get; set; }     } 

the logic compile object follows:

function createobject() {     var routemodel = { checkpoints: [] ,totaldistance:totaldistance};     (var = 0; < markersorders.length; i++) {         var latlng = markersorders[i].getposition();         var checkpoint = {             'latitude': latlng.lat(),             'longitude': latlng.lng()         };         routemodel.checkpoints.push(checkpoint);     }     return json.stringify(routemodel); } 

here's ajax method:

function saveroute() {     var apiurl = location.origin + "/map/addroute";     $.ajax({         method: "post",         url: apiurl,         contenttype: "application/json;charset=utf-8",         data: (createobject())     }).done(function (msg) {         alert("data saved: " + msg);     }).error(function(msg){alert("error: "+ msg)}); } 

the controller receiving post follows:

        [httppost]         [validateantiforgerytoken]         public iactionresult addroute([frombody]routeviewmodel route)         {             routeviewmodel newroute = route;             if (modelstate.isvalid)             {                 _context.addroute(newroute.checkpoints, newroute.totaldistance);                 _context.saveroute();                 return redirecttoaction("savedroutes");             }             else             {                 return badrequest(modelstate);             }         } 

here raw post:

post https://localhost:44343/map/addroute http/1.1 host: localhost:44343 connection: keep-alive content-length: 290 accept: */* origin: https://localhost:44343 x-requested-with: xmlhttprequest user-agent: mozilla/5.0 (windows nt 10.0; wow64) applewebkit/537.36 (khtml, gecko) chrome/51.0.2704.103 safari/537.36 content-type: application/json;charset=utf-8 referer: https://localhost:44343/map/map accept-encoding: gzip, deflate, br accept-language: en-us,en;q=0.8 cookie: .aspnetcore.antiforgery.4ise6xvgxqo=cfdj8hmvr1mwbstlrog_4rxm-sje_smjzyd-gbopg5e19rchqlc61xsnewa7yogiysc-u63ith6cd0ggwqwmwdpjoibpkrxlctls_a_b3wmpvai80vyux6j0lckfn24gbf7x_xzhal3eac892j7ydjwa9oc; .aspnetcore.identity.application=cfdj8hmvr1mwbstlrog_4rxm-shk66uthf3kfjjezcs7hctztr-sejhxvj8l5ms66u4ewd72nexujebaifhixfzvhjzzjiqsvflcxdhnmcsbywxggamaa_sbjdimnqxnpac-nmtp_fdetcpjeob1lby1hl-gfqaajdrzvrcc7ochwtsbvz9jdhmm0htnychcj8bucczh8fhvnpefzlcm_rer8u2vsqroxy_zmczduq_mqcmtvlgddrrjwhlhuafrz2mmaxq1idzqhprtv98qax2zm4tsoaobkoealq_oa2n1sdvfmmtgsedb1mlsj-lkplkhccmtb14kwdrctvotxoqcbqtffjhllc5405_dccqjwj3mittn1ss3x1ahup-phhzfx9zhusq1-iqv4ppds12c1q2b5uz0qeohaubyvee5bkpzkltt2kxnw1v81agmmmwbi9zfkuh9nufnqmgcqf5vxsx-ftm-udwzgymnk0jpg7k4cpiseycv9soep1qulz-p28rxlhcvqyax3ficcrfoqmf63tu5ofvhu1bhrdv_nqalhbpku9nrxfyxxece5wrc4it-kcliaoqblya9bewb80qiwis-whndy5vvcdakd2d5  {"checkpoints":[{"latitude":-34.004057732693184,"longitude":25.649633891880512},{"latitude":-34.00313273259371,"longitude":25.65392542630434},{"latitude":-34.001425013635725,"longitude":25.653367526829243},{"latitude":-34.00019756942711,"longitude":25.650320537388325}],"totaldistance":919} 

as advised @kiran challa collected modelstate errors in controller , wrote output window this:

        [httppost]         [validateantiforgerytoken]         public iactionresult addroute([frombody]routeviewmodel route)         {             routeviewmodel newroute = route;             if (modelstate.isvalid)             {                 _context.addroute(newroute.checkpoints, newroute.totaldistance);                 _context.saveroute();                 return redirecttoaction("savedroutes");             }             else             {                 //getting errors                 var errors = modelstate.values.selectmany(v => v.errors);                 debug.writeline("errors found: "+ errors+"\nend errors found");                 return badrequest(modelstate);             }         } 

in output window when trigger controller, receive this:

microsoft.aspnetcore.antiforgery.antiforgeryvalidationexception: required antiforgery header value "requestverificationtoken" not present.    @ microsoft.aspnetcore.antiforgery.internal.defaultantiforgery.<validaterequestasync>d__9.movenext() --- end of stack trace previous location exception thrown ---    @ system.runtime.compilerservices.taskawaiter.throwfornonsuccess(task task)    @ system.runtime.compilerservices.taskawaiter.handlenonsuccessanddebuggernotification(task task)    @ microsoft.aspnetcore.mvc.viewfeatures.internal.validateantiforgerytokenauthorizationfilter.<onauthorizationasync>d__3.movenext() microsoft.aspnetcore.mvc.internal.controlleractioninvoker:warning: authorization failed request @ filter 'microsoft.aspnetcore.mvc.viewfeatures.internal.validateantiforgerytokenauthorizationfilter'. microsoft.aspnetcore.mvc.statuscoderesult:information: executing httpstatuscoderesult, setting http status code 400 microsoft.aspnetcore.hosting.internal.webhost:information: request finished in 37.4837ms 400  

try having createobject() return this:

function createobject() {     var routemodel = { checkpoints: [] ,totaldistance:totaldistance};     (var = 0; < markersorders.length; i++) {         var latlng = markersorders[i].getposition();         var checkpoint = {             'latitude': latlng.lat(),             'longitude': latlng.lng()         };         routemodel.checkpoints.push(checkpoint);     }     return json.stringify({route: routemodel}); } 

Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

http - Safari render HTML as received -