I've read several StackOverflow posts about this and corrected my code several times
but I cant get my webAPI post method to work. I'm trying to receive a post parameter
but it comes always null.
What I am trying to do is receiving a base64 string that represents a canvas that is
creating with jquery when the user clicks the button:
function MakePhoto(ctrl) {
html2canvas(ctrl, {
onrendered: function (canvas) {
var canvasData = canvas.toDataURL()
jQuery.ajax({
url: "../api/webinfo",
type: "POST",
data: { imagedata: canvasData },
success: function () {
alert("success");
},
error: function () {
alert("failure");
}
});
}
});
}
my WebInfoController.cs looks like this:
public void Post([FromBody]string imagedata)
{
}
imagedata parameter comes always NULL
And this are the headers I am receiving at webapi:
"Method: POST,
RequestUri: 'http://myhost/RestFulApi/api/webinfo'
Content: System.Net.Http.StreamContent
User-Agent: Chrome/27.0.1453.94
Content-Length: 42226
Content-Type: application/x-www-form-urlencoded; charset=UTF-8}
I hope you could help me.
Thanks
OK, I found the problem after some hours researching. I had to pass the data parameter to ajax function using:
"=" + canvasdata, without the parameter name:
jQuery.ajax({
url: "../api/webinfo",
type: "POST",
data: "=" + canvasData,
success: function (response) {
alert(response);
},
error: function (response) {
alert(response.responseText);
}
});
Related
I have a http://localhost:54393/CreateTest/4fwp36 which working fine but when I call http://localhost:54393/CreateTest/RemoveControlsNew from jQuery ajax then it is not working giving an error also not calling into a controller if any one can help me out as I am stuck here more then 1 day
I have tried this but it's not working:
MVC JQuery call from url without action
This is my route config:
routes.MapRoute(
name: "CreateTest",
url: "CreateTest/{id}",
defaults: new { controller = "CreateTest", action = "Index", id = UrlParameter.Optional }
);
Above code works perfectly when I call from another controller calling it like this:
return Redirect("/CreateTest/"+ strTestID);
When I try to call on same controller with ajax post method
RemoveControls: function (rid) {
var MyAppUrlSettings = {
MyUsefulUrl: "/CreateTest/RemoveControlsNew"
}
$.ajax({
type: 'POST',
dataType: "JSON",
async: false,
//url: '#Url.Action("RemoveControlsNew",Request.Url.Scheme)',
url: MyAppUrlSettings.MyUsefulUrl,
contentType: 'application/json; charset=utf-8',
data: {
rid: rid,
bgcolor: CREATETEST.globalbgcolor,
fontcolor: CREATETEST.globalfontcolor,
fontsize: CREATETEST.globalfontsize
},
success:
function (response) {
var data = response;
if (data == 'Error') {
CREATETEST.showerror('Some thing went wrong you cannot remove a question at the moment for selected option');
}
else {
$("#AddControlNew").load(location.href + " #AddControlNew");
}
},
error:
function (response) {
console.log(response);
CREATETEST.showerror("Error: " + response);
}
});
},
Then these is not working and my method is not called.
I am getting this error:
Error on page
Controller code for Ajax call
Regular Controller code
Your "Error on Page" image doesn't show anything useful, are you getting a 404, 202, 405 Header Status Code
Please post code, not images.
Apply the [FromBody] attribute to a parameter to populate its properties from the body of an HTTP request. The ASP.NET Core runtime delegates the responsibility of reading the body to an input formatter.
public JsonResult RemoveControlsNew([FromBody] int rid, string bgcolor, string fontcolor, string fontsize)
I have a ASP.Net web API with one post method. I'm calling the post method from angular js. It is not passing me the data to API POST method, All my properties of my requestData object is null. I'm not sure what is the mistake am doing here. Can anyone help me plz.
API Code
public void Post(RequestData data)
{
.....
}
public class RequestData
{
PropertyDetail propertyDetails;
ICollection<Model1> model1s;
ICollection<Model2> model2s;
ICollection<Model3> model3;
ICollection<Model4> model4;
}
Client Code
var requesData = new RequestData();
requesData.model0= $scope.model0;
requesData.model1s= $scope.models;
requesData.model2s= $scope.model2s;
requesData.model3s= $scope.model3s;
requesData.model4s= $scope.model4s;
$http({
method: 'POST',
url: window.apiUrl,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: requesData,
}).then(function (res) {
console.log('succes !', res.data);
window.alert("Successfully created");
}).catch(function (err) {
debugger;
console.log('error...', err);
});
Probably, your server side couldn't map your parameters correctly. Data type matching is important while post some parameters. You can change your client code like this:
...
contentType: "application/json; charset=utf-8",
data: JSON.stringify(requestData),
dataType:'json',
...
After doing as #Jaky71 says, you can learn how .net expects those objects by calling dummy methods with nulls or whatever you nees to mimic.
.net has a strict parser
You can use angular.toJson:
$http({
method: 'POST',
url: window.apiUrl,
headers: { 'Content-Type': 'application/json' },
data: angular.toJson(requesData),
}).then(function (res) {
console.log('succes !', res.data);
window.alert("Successfully created");
}).catch(function (err) {
debugger;
console.log('error...', err);
});
Also make sure that your properties match.
I've tries setting breakpoints at the Controller method. But it does not stop there. The alerts "clicked" and the next one work perfectly fine. But the controller method is not called. Any help is appreciated. Here's my ajax call and my controller method.
var Url = "#Url.Action("~/Home/Get_Location")";
$("#gotoloc").click(function() {
alert("clicked");
alert(lat +" "+ lon);
$.ajax({
type: "POST",
url: Url,
data: {
latitude: lat,
longitude: lon
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert("Hello:" + response)
},
failure: function(response) {
alert(response.responseText);
},
error: function(response) {
alert(response.responseText);
}
});
alert("ignored");
});
public JsonResult Get_Location(double latitude,double longitude)
{
string loc = latitude + "/" + longitude;
return Json(loc, JsonRequestBehavior.AllowGet);
}
You are using the Url.Action method incorrectly.
Try this
var Url = "#Url.Action("Get_Location","Home")";
The above overload takes the action method name as first parameter and controller names as second parameter
Also, i see you are passing incorrect contentType request header. contentType headers tells the server what is the type of data the client is sending. Your current code says you are sending json data. But you have 2 parameters in your action method and the json serializer will fail to properly map the posted data to it, hence you will be getting a 500 response from the server.
This should work, assuming there are no other js errors in your page
var url = "#Url.Action("Get_Location","Home")";
$.ajax({
type: "POST",
url: url,
data: { latitude: 44, longitude: 55 },
success: function (response) {
console.log("Hello:" + response);
},
failure: function (response) {
console.log(response.responseText);
},
error: function (response) {
console.log(response.responseText);
}
});
In a Post method within a Controller derived from ApiController what should I return to indicate success to jQuery ?
I've tried HttpResponseMessage but jQuery sees this as an error (even though the argument the jQuery error handler clearly has a 200 status).
The jQuery looks like this :
processParticipantEvent: function(parID, evtType, evtNotes, successFunction, errorFunction){
debugger;
var requestURL = '/api/participantevent';
var json = {"parId" : parID, "evtType": evtType, "evtNotes": evtNotes};
var jsonArray=JSON.stringify(json);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: requestURL,
data: jsonArray ,
dataType: "json",
success: function (data) { successFunction(data); },
error: function (data) { errorFunction(data); }
});
},
I've read this : Ajax request returns 200 OK, but an error event is fired instead of success which seems like it's touching on the same issue but I suspect it's out of data as it won't work for me ?
Just to be clear all I want to do is to return a plain old 2xx with no data.
As per the documentation:
"json": Evaluates the response as JSON and returns a JavaScript
object. Cross-domain "json" requests are converted to "jsonp" unless
the request includes jsonp: false in its request options. The JSON
data is parsed in a strict manner; any malformed JSON is rejected and
a parse error is thrown. As of jQuery 1.9, an empty response is also
rejected; the server should return a response of null or {} instead.
So if you want to use jQuery ajax you have to return a valid json string, just use the following in your API controller:
return Ok(new {});
Note this is a jQuery ajax "feature", using Angular for example to do an ajax post I can use return Ok(); inside my controller and everything works as expected.
As mentioned by #Beyers the return with OK() just works.
I've created the same structure here and worked.
My Controller has this:
[Route("api/participantevent")]
public IHttpActionResult Test()
{
return Ok("");
}
And at client I've changed your function just to simplify:
processParticipantEvent= function(){
debugger;
var requestURL = '/api/participantevent';
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: requestURL,
data: [{'test': '1'}] ,
dataType: "json",
success: function (data) { alert('success'); },
error: function (data) { alert('error'); }
});
}
Your error is with the requestURL. Its value is absolute and http://api/participantevent does not exist. Try using a relative value.
var requestURL = './api/participantevent';
It seems that if you get an OK response, It is probably not a valid JSON.
I would recommend to you to check the HTTP response in the browser and try to run the JSON.parse function with the responseText and see whether it fails.
I usually declare a class like below:
public class AjaxResult
{
private bool success = true;
private List<string> messages;
public bool Success { get { return success; } set { success = value; } }
public List<string> Messages { get { return messages; } }
public AjaxResult()
{
messages = new List<string>();
}
}
In the controller, the action(to which the ajax request is made) should have JsonResult as return type.
[HttpPost]
public JsonResult Action(string id)
{
AjaxResult result = new AjaxResult();
//Set the properties of result here...
result.Success = true;
result.messages.Add("Success");
return Json(result);
}
3.And your ajax call will look like this:
$.ajax({
type: "POST",
dataType: 'json',
url: /ControllerName/Action,
data: { id: "Test"},
success: function (data) { alert('success'); },
error: function (data) { alert('error'); }
});
I have the following request:
var response = $.ajax({
type: "POST",
contentType: "application/x-www-form-urlencoded",
url: this.AgentServiceUrl + "/" + methodName,
data: data,
async: this.Async,
success: function (xml, textStatus) { if (successHandler != null) successHandler(state, $.xml2json(xml), textStatus); },
error: function (xmlHttpRequest, textStatus, errorThrown) { if (errorHandler != null) errorHandler(state, xmlHttpRequest, textStatus, errorThrown); }
});
I want to add to a variable to this request header and consume it on C#,
I try many ways but I can't consume it on C#:
beforeSend: function (req)
{
req.setRequestHeader("AgentGUID", this.AgentGUID);
},
Pass parameters:
Can you help me? I don't want to change the function at the C# part I just want to use something like:
(System.Web.HttpContext.Current.Request.Headers["someHeader"]
Your beforeSend should work as you wish, but the reason you are not getting the value on server side is that this.AgentGUID on this method call is undefined because this in that context is pointing to another object (most probably ajax request object).
By defining a variable outside your ajax call you issue will be fixed.
var me = this;
var response = $.ajax({
...
beforeSend: function (req)
{
req.setRequestHeader("AgentGUID", me.AgentGUID);
},
...
});