Reputation: 1747
I tried everything yet still when debugging the value at the web api post action is always null. i tried changing the headers, i added [JsonObject(MemberSerialization.OptOut)] above the posted model class, i tried a simple Dto. nothing works... this is the controller function that passes the user data:
$scope.Add = function () {
var user = {
ID: $scope.ID,
FirstName: $scope.FirstName,
LastName: $scope.LastName,
Age: $scope.Age,
Address: $scope.Address
};
$scope.usersRepo.push(user);
myService.addUser(user);
the service function is:
var addUser = function (user) {
return $http.post(
usersApi + '/addNewUser',
JSON.stringify(user)),
{
headers: {
'Content-Type': 'application/json'
}
};
};
and the web api action is:
[HttpPost, ActionName("addUser")]
public void Post([FromBody]UserModel value)
{
UsersDB.Add(value);
}
my model is this:
[JsonObject(MemberSerialization.OptOut)]
public class UserModel
{
public UserModel()
{
}
public UserModel(string firstName, string lastName, int age, string address)
{
this.Address = address;
this.Age = age;
this.FirstName = firstName;
this.LastName = lastName;
}
public void ConvertDto(UserDto userDto)
{
ID = userDto.ID;
FirstName = userDto.FirstName;
LastName = userDto.LastName;
Age = userDto.Age;
Address = userDto.Address;
}
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string Address { get; set; }
}
Upvotes: 0
Views: 62
Reputation: 3718
Use http post method like this. data should be your object to be passed without json stringify. I advised you to create a service for http methods.
var obj = {
url: your url,
async: true,
method: 'POST',
headers: {
"content-type": "application/json; charset=utf-8",
}
};
if (typeof data != 'undefined' && typeof data != null) {
obj.data = data;
}
$http(obj).then(function() {}, function() {});
Service : // http methods
app.service('MethodProvider', ['$http', function ($http) {
var self = this;
self.get = function (url, data) {
var obj = {
url: url,
async: true,
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
};
if (typeof data != 'undefined' && data != null) {
obj.params = data;
}
return $http(obj);
};
self.post = function (url, data) {
var obj = {
url: url,
async: true,
method: 'POST',
headers: {
"content-type": "application/json; charset=utf-8",
}
};
if (typeof data != 'undefined' && typeof data != null) {
obj.data = data;
}
return $http(obj);
};
self.put = function (url, data) {
var obj = {
url: url,
async: true,
method: 'PUT',
headers: {
'Content-Type': 'application/json'
}
};
if (typeof data != 'undefined' && data != null) {
obj.data = JSON.stringify(data);
}
return $http(obj);
};
self.delete = function (url) {
var obj = {
url: url,
async: true,
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
}
};
if (typeof data != 'undefined' && data != null) {
obj.data = JSON.stringify(data);
}
return $http(obj);
};
}]);
Upvotes: 0