asp.net web api - Get error when I try to make AJAX POST call -
i create view in action page:
public class homecontroller : controller { public actionresult index() { viewbag.title = "home page"; return view(); } } at point in view make post call another controller using ajax:
function save() { if (sensordata) { $.ajax({ url: '/../sensor/savedata', type: 'post', contenttype: 'application/json', datatype: 'json' }); } else { alert("no data."); } } this code of api controller:
public class sensorcontroller : apicontroller { public ihttpactionresult savedata() { try { return ok(); } catch (exception) { return badrequest("data not saved"); } } } but error: "networkerror: 404 not found - http://localhost:7486/sensor/savedata"
any idea why error?and how solve problem.
it looks trying call api controller mvc route. if check webapiconfig have got defaultapi route defined:
config.routes.maphttproute( name: "defaultapi", routetemplate: "api/{controller}/{id}", defaults: new { id = routeparameter.optional } ); if case change controller action add [httppost] attribute
public class sensorcontroller : apicontroller { [httppost] public ihttpactionresult savedata() { try { return ok(); } catch (exception) { return badrequest("data not saved"); } } } then make ajax call:
function save() { if (sensordata) { $.ajax({ url: '/api/sensor', type: 'post', contenttype: 'application/json', datatype: 'json' }); } else { alert("no data."); } } note: don't appear @ point posting data server.
Comments
Post a Comment