Model parameter passed (HTTP POST) to Web API 2 from AngularJS is null - angularjs

I am making a POST request from Angular to Web API 2:
let params = {
ReportName: reportName,
ParamName: paramName,
ParamValues: paramValues
};
this.$http.post("/reportsweb/api/reports/", params).then(response => {
deferred.resolve(response.data);
}, response => {
deferred.reject(response);
})
Web API method is defined like this:
[HttpPost]
[ResponseType(typeof(Dictionary<string, string>))]
public IHttpActionResult GetDependentParameterValues([FromBody]ArgumentModel args)
{
// args here is null for some reason
}
where ArgumentModel is defined the same way as params var in Angular:
public class ArgumentModel
{
public string ReportName { get; set; }
public string ParamName { get; set; }
public string ParamValues { get; set; }
}
However, when I hit a breakpoint in WebAPI method, I see that args = null :(
Any idea why?
Thanks.
Here is the screenshot from angular app:

Related

Postman POST working but AngularJS post throwing 404

I'm just trying to pass some basic form data through to a web-api via AngularJS $http.
here is the function that called to send data to the API:
$http({
url: "/Portal/GenerateTimeSheets",
method: "POST",
headers: {
'Content-Type': 'application/json'
},
data: angular.toJson($scope.placementForm),
}).then(function (response) {
}), function(response) {
};
Note: if I breakpoint and copy and paste the $scope.placementForm data into postman it works completely fine, but going through a browser is throwing errors.
Here is my api:
[HttpPost]
public void GenerateTimeSheets([FromBody]PlacementModel placement)
{
Console.WriteLine("STUB");
}
and the Placement Model:
[JsonProperty(PropertyName = "candidateName")]
public string CandidateName { get; set; }
[JsonProperty(PropertyName = "clientName")]
public string ClientName { get; set; }
[JsonProperty(PropertyName = "jobTitle")]
public string JobTitle { get; set; }
[JsonProperty(PropertyName = "placementStartDate")]
public string StartDate { get; set; }
[JsonProperty(PropertyName = "placementEndDate")]
public string EndDate { get; set; }
[JsonProperty(PropertyName = "frequency")]
public string TimeSheetFrequency { get; set; }
404 Usually denotes that the url of the request is wrong, You are missing something in the url. Validate your url with the backend. Hope it helps

Angular js posting object to web API is null

I am posting form data to webAPI and one of object has boolean value(i.e from checkbox; Deviceselected has boolean values here in code).this object returns null in my api controller.
I tried declaring Desktop and Mobile as string in controller.That did not fix as well.
What am i missing in here?
I'm able to post other data except Deviceselected
Angualrjs controller code
$scope.SendData = function (Data) {
var GetAll = new Object();
GetAll.Redirection = Data.redirection;
GetAll.Deviceselected = new Object();
GetAll.Deviceselected.Desktop = Data.devSelected.desktop;
GetAll.Deviceselected.Mobile = Data.devSelected.mobile;
GetAll.Protocol = Data.protocol;
$http({
url: "http://localhost:61352/api/Market",
dataType: 'json',
method: 'POST',
data: GetAll,
headers: {
"Content-Type": "application/json"
}
}).then(successCallback, errorCallback);
};
})
Web API code
public class SubmitData
{
public string Redirection { get; set; }
public Deviceselected deviceSelected;
public string Protocol { get; set; }
}
public class Deviceselected
{
public Boolean Desktop { get; set; }
public Boolean Mobile { get; set; }
}
[HttpPost]
public string sendData(HttpRequestMessage request,[FromBody] SubmitData marketModel)
{
return "Data Reached";
}
Apparently it works with the same logic.1)Cleared cache 2)Run API and then load HTML

MVC Core Action not binding from angularjs POST

I'm having a problem by where I am posting an object to an MVC Core controller from a simple angularjs page.
The object at my MVC action is not binding although the object itself isn't null which is the usual problem with this.
Can anyone see what I am doing wrong?
This is my angular service code:
this.getQuote = function (priceRequest) {
return $http.post('/quote/getcost', { priceRequest });
};
which is called by:
quoteService.getQuote(this.quoteData).then(function (cost) {
$scope.quoteData.quoteCost = cost.data;
});
where this.quoteData is:
$scope.quoteData = {
detailLevel: '0',
fileLengthHours: 0,
fileLengthMinutes: 1,
excessiveSpeakersCount: 1,
industry: null,
deliveryTime: '1',
additionalInformation: '',
quoteCost: null
};
This is the payload
and this is the POST:
Finally my C# MVC Core action:
[HttpPost]
public JsonResult GetCost([FromBody]PriceRequest priceRequest)
{
var price = _priceCalculator.GetPrice(priceRequest);
return new JsonResult(price);
}
Although the object posted in is not null, none of the values have been bound:
This is the PriceRequest object:
public class PriceRequest
{
public JobDetailLevel DetailLevel { get; set; }
public int FileLengthHours { get; set; }
public int FileLengthMinutes { get; set; }
public int? ExcessiveSpeakersCount { get; set; }
public JobIndustry Industry { get; set; }
public JobDeliveryTime DeliveryTime { get; set; }
public string AdditionalInformation { get; set; }
}
Can anyone see what I am doing wrong?
Ok so courtesy of this post:
Asp.net core MVC post parameter always null
I needed to add this to my startup.cs:
.AddJsonOptions(jsonOptions =>
{
jsonOptions.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
});
Thanks to those who tried to help.
Try removing the { } from around the priceRequest variable on the angular side.
Like:
return $http.post('/quote/getcost', priceRequest);

How to pass two different types parameters in http POST method using angularjs to Web API?

First parameter is a complex type object(JSON) and second parameter is a simple type(String).Here I am using Web API 2.
I am putting my code below.
Web API
public class UserDetailsModel
{
[Key]
[EmailAddress]
public string LoginEmail { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Password { get; set; }
public string DisplayPic { get; set; }
[EmailAddress]
public string AlternateEmail { get; set; }
public string Organization { get; set; }
public string Occupation { get; set; }
public string Contact { get; set; }
public DateTime DoB { get; set; }
public string Gender { get; set; }
public string Country { get; set; }
public string State { get; set; }
public string City { get; set; }
public string Website { get; set; }
public string Info { get; set; }
public DateTime DateOfRegister { get; set; }
//public string LoginIP { get; set; }
public int LoginFlag { get; set; }
}
public int RegisterUser(UserDetailsModel userReg, string LoginIP)
{
.
.
.
}
angularjs
var UserDetails = {
'LoginEmail': $scope.LoginEmail,
'LoginName': $scope.LoginName,
'Password': $scope.Password,
'DoB': $scope.DoB,
'Gender': $scope.Gender,
'City': $scope.City,
'State': $scope.State,
'Country': $scope.Country
};
var request = $http({
method: 'post',
url: urlBase + '/UserDetails',
params: { 'userRegJSON': UserDetails, 'LoginIP': LoginIP }
});
Here in above code, I am getting NULL in UserDetails and 192.152.101.102 in LoginIP in Web API.
var request = $http({
method: 'post',
url: urlBase + '/UserDetails',
data: { 'userRegJSON': UserDetails, 'LoginIP': LoginIP }
});
Here in above code, I am getting NULL in both parameter UserDetails and LoginIP in Web API.
Then how to pass two or more different parameter types in http POST method using angularjs.
You cannot pass 2 types in webAPI.Either you pass everything in a single type or you can do the below
var request = $http({
method: 'post',
url: urlBase + '/UserDetails?LoginIp=' + LoginIP,
data: UserDetails,
});
In the API change the signature to
public int RegisterUser([FromBody]UserDetailsModel userReg, [FromUri]string LoginIP)
{
.
.
.
}
Go throught this:
Use simple and complex types in my api method signatures
POST multiple objects from Angular controller to Web API 2
Webapi doesn't work fairly well when you wish to pass 2 parameters in a POST
method. ModelBinding in Webapi always works against a single object because it maps a model.
There a few workarounds that you can use to make this work:
Use both POST and QueryString Parameters in Conjunction
If you have both complex and simple parameters, you can pass simple parameters on the query string. Your code should actually work with:
something like this
/baseUri/UserDetails?LoginIP=LoginIP
but that's not always possible. In this example it might not be a good idea to pass a user token on the query string though.
Refer to #Ravi A's suggestions for making changes in your code.

Send IEnumerable from web api controller to angular js

I'm trying to send a IEnumerable from a web api controller to a AngularJs controller.
The code I was using was
Web Api:
readonly InventoryEntities _db = new InventoryEntities();
public IEnumerable<FDVOEligibilityRequest> Get()
{
return _db.FDVOEligibilityRequests.AsEnumerable();
}
AngularJS:
//get all customer information
$http.get("/api/Customer/").success(function (data) {
$scope.requests = data;
$scope.loading = false;
})
.error(function () {
$scope.error = "An Error has occured while loading posts!";
$scope.loading = false;
});
This worked fine, but now I'm using linq to include related tables and it doesn't work. The angularJs code is the same.
What am I doing wrong?
readonly InventoryEntities _db = new InventoryEntities();
public IEnumerable<FDVOEligibilityRequest> Get()
{
return _db.FDVOEligibilityRequests
.Include("FDVOEligibilityRequestMandatoryField")
.Include("FDVOEligibilityRequestDCCField").AsEnumerable();
}
I do get the data I want in the controller, but when i try to send it back to angular, I get a 500 (Internal Server Error) angular.js:10722
This is what FDVOEligibilityRequest looks like in the new Web Api controller
public partial class FDVOEligibilityRequest
{
public int Id { get; set; }
public string TestName { get; set; }
public string GroupName { get; set; }
public int MandatoryFieldsID { get; set; }
public int DCCFieldsID { get; set; }
public virtual FDVOEligibilityRequestMandatoryField FDVOEligibilityRequestMandatoryField { get; set; }
public virtual FDVOEligibilityRequestDCCField FDVOEligibilityRequestDCCField { get; set; }
}
If it's 500 and happens after you successfully make a return from your action then it can be an exception during serialization.
I would suggest to check that there are no circular references between FDVOEligibilityRequest and FDVOEligibilityRequestMandatoryField/FDVOEligibilityRequestDCCField.
Or try to diagnose it using code from here:
string Serialize<T>(MediaTypeFormatter formatter, T value)
{
// Create a dummy HTTP Content.
Stream stream = new MemoryStream();
var content = new StreamContent(stream);
/// Serialize the object.
formatter.WriteToStreamAsync(typeof(T), value, stream, content, null).Wait();
// Read the serialized string.
stream.Position = 0;
return content.ReadAsStringAsync().Result;
}
try {
var val = _db.FDVOEligibilityRequests
.Include("FDVOEligibilityRequestMandatoryField")
.Include("FDVOEligibilityRequestDCCField").AsEnumerable();
var str = Serialize(new JsonMediaTypeFormatter(), val);
}
catch (Exception x)
{ // break point here
}
ps: the common suggestion in this case is to use DTOs instead of EF objects with something like Automapper.

Resources