$http post passing value as null to Asp.Net Web API - c#

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.

Related

Parameter null in C# code but it is set in AJAX call

I'm developing an ASP.NET MVC 5 application with C#, .NET Framework 4.7 and jQuery 1.11.2.
This javascript code:
function RequestCodes(button, poId) {
var URL = '/ProductionOrder/RequestCodeForIncompleteOrder';
//button.attr("disabled", "disabled");
$('#ok').hide();
$('#fail').hide();
$('#cargando').show();
$.ajax({
url: URL,
type: "PUT",
dataType: "HTML",
data: { productionOrderId: poId },
contentType: "json",
success: function () {
$('#cargando').hide();
$('#ok').show();
$("#ok").fadeOut("slow", function () {
$('#ok').hide();
});
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
$('#cargando').hide();
$('#fail').show();
$("#fail").fadeOut("slow", function () {
$('#fail').hide();
//button.removeAttr("disabled");
});
}
});
}
Throws this error:
he parameters dictionary contains a null entry for parameter
'productionOrderId' of non-nullable type 'System.Int32' for method
'System.Web.Mvc.ActionResult RequestCodeForIncompleteOrder(Int32)' in
'TRZF.Web.API.Controllers.ProductionOrderController'. An optional
parameter must be a reference type, a nullable type, or be declared as
an optional parameter.Parameter name: parameters.
When I call the method:
public ActionResult RequestCodeForIncompleteOrder(int productionOrderId)
The problem is with the parameter name in the javascript code, but I don't know how why because it has the same name like in the C# code.
How can I fix this error?
Here is the solution:
you have syntax error at below line. I have fixed this.
data: "{'productionOrderId':'" + poId + "'}",
I have found the problem.
$.ajax({
url: URL,
type: "PUT",
data: { productionOrderId: poId },
success: function () {
$('#cargando').hide();
$('#ok').show();
$("#ok").fadeOut("slow", function () {
$('#ok').hide();
});
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
$('#cargando').hide();
$('#fail').show();
$("#fail").fadeOut("slow", function () {
$('#fail').hide();
//button.removeAttr("disabled");
});
}
});
I have removed dataType: "HTML", and contentType: "json",, and now it works.
I have done another test, removing only contentType: "json", and it works. So, I think the problem is with setting the contentType.
at controller RequestCodeForIncompleteOrder function you need to get productionOrderId with nullable data type like following :
RequestCodeForIncompleteOrder(int? productionOrderId)
{
//your code here
}
? mean accept nullable data type
changing the content type to "application/json" and strigifying the data fixed the issue for me.
here is the sample code.
$.ajax({
url: "/Home/RequestCodeForIncompleteOrder",
type: "POST",
dataType: "json",
data: JSON.stringify({
productionOrderId: 1
}),
contentType: "application/json",//change "json" to "application/json"
success: function () {
console.log("success");
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("error");
}
});
First of, is your route to the api correct?
Usually it's prefixed with api/..
Secondly, the client model that you are sending to the server is not matching the expected value type (int) on the server side.
Option 1 is to match the server side with the client side object.
Your client object { productionOrderId: poId } is equal to a server side model defined as this
public class RequestModel
{
public int productionOrderId { get; set; }
}
Use the model in the api controller method and read it from the body
public ActionResult RequestCodeForIncompleteOrder([FromBody]RequestModel model){}
NOTE: Don't forget to stringify the object before sending it in the client when using content type application/json, data: JSON.stringify({ productionOrderId: })
Option 2 is to send the productionOrderId in the route
[RoutePrefix("api/ProductionOrder")]
public class ProductionOrder : ApiController
{
[HttpPut]
[Route("RequestCodeForIncompleteOrder/{productionOrderId}")]
public ActionResult RequestCodeForIncompleteOrder(int productionOrderId){}
}
Then call this method by using url api/ProductionOrder/RequestCodeForIncompleteOrder/2345 where 2345 is your order id

AJAX Call not hitting Controller Method - ASP.NET MVC

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);
}
});

.NET (ApiController) / jQuery .ajax : what to return from POST?

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'); }
});

JSON and other parameters in data property of AJAX PUT. ASP.net Web API

I want to send a JSON object and values from text boxes back to my controller, but I am having trouble. I can send just the JSON object successfully, but as soon as I add other parameters I get an error saying the requested resource does not support http method 'PUT'. I have tried commenting out the contentType and using Data: {viewModel: JSON.stringify(jsonData), userName: username}, without any success (I eventually will add more string parameters). Below is my ajax and controller signature. Thanks in advance.
$.ajax({
type: 'PUT',
contentType: 'application/json',
url: 'api/Label',
cache: false,
data: JSON.stringify(jsonData),
success: function (result) {
// TODO
},
error: function (HttpRequest, textStatus, err) {
var response = jQuery.parseJSON(HttpRequest.responseText);
$('#LabelInfo').show();
$('#LabelInfo').text('Error: ' + response.ModelState["viewModel.Pieces"][0]);
}
});
controller signature:
public HttpResponseMessage Put(Label viewModel, string
userName)

Null parameters doing HTTP POST from Ajax to Web API

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);
}
});

Categories