How to send post request through Angular to ASP.net web API - angularjs

I am new to both angular and ASP.NET web API. in angular i get values from a form and try to pass it to the server through post request her is the code for angular.
app.controller('AddTrnController',['$scope', 'CategoriesService','$http', function($scope, CategoriesService, $http){
$scope.categories =[{}];
$scope.AddTrn = {};
function init(){
CategoriesService.getCategories("1")
.success(function(data){
$scope.categories = data;
})
.error(function(data, status, headers){alert(status);});
}
init();
$scope.change= function(option){
$scope.AddTrn.TrnID = option.CatID;
$scope.AddTrn.TrnAccount = 1;
};
$scope.UpdateTrans=function(){
alert("21312");
$http({method:"post",
url:'http://localhost:18678/api/Transaction',
params:"data:$scope.AddTrn"}
).success(function(){alert("succeeded");
}).error(function(){alert("faild");});
};
}]);
And her the the code for web API.
public HttpResponseMessage PostTransaction(String transaction)
{
if (ModelState.IsValid)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, transaction);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = transaction}));
return response;
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
I always get failed response from angler and when i make breakpoint in API it dose not trigger.

The params option that you are using adds items to the query string, for a post you will probably want to use the data option instead, try changing the code to this:
$scope.UpdateTrans=function(){
alert("21312");
$http({method:"post",
url:'http://localhost:18678/api/Transaction',
data:$scope.AddTrn
}
).success(function(){alert("succeeded");
}).error(function(){alert("faild");});
};

Related

I send http post request with angular but it does not go to the asp.net mvc action and returns html layout tags

I am doing an angular application with asp.net mvc and i made a registration form with identity, I have layout and index mvc view which i just write in it ng-view tag and i inject html pages in it, I am doing a http post request from angular controller to mvc action method but the request does not go to the mvc action, whereas when i change th views to mvc views and make a templateUrl in angular map to mvc method it works well.
Can any one help me in this problem.
[HttpPost]
[AllowAnonymous]
public async Task<JsonResult> Register(RegisterViewModel model)
{
string message = "";
if (ModelState.IsValid)
{
var user = new ApplicationUser
{
FirstName = model.FirstName,
MiddleName = model.MiddleName,
LastName = model.LastName,
UserName = model.Email,
Email = model.Email,
UserStatus = UserStatus.Waiting
};
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
message = "Success";
}
else
{
AddErrors(result);
message = "InvalidEmail";
}
}
else
{
message = "Failed!";
}
return new JsonResult { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
and this is my angular controller
MyApp.controller('RegisterController', ['$scope','$http',function ($scope, $http) {
$scope.message = '';
$scope.isFormValid = false;
//Check Form Validation
$scope.$watch('f1.$valid', function (newValue) {
$scope.isFormValid = newValue;
});
//Save Data
$scope.SaveData = function (data) {
$scope.submitted = true;
$scope.message = '';
if ($scope.isFormValid) {
$http({
method: 'POST',
url: '/Account/Register',
data: data
}).then(function (response) {
// check your response (if a success status code was resolved)
console.log(response.data);
}, function (error) {
// check your error response
console.log(error);
});
} else {
$scope.message = "Please Fill the blanks";
}
}
}]);
and this is my html page:
<div ng-controller="RegisterController">
<form name="f1" ng-submit="SaveData(user)" novalidate>
controls here
</form
1) Check your browser console for any javascript errors, if you have any, resolve them and try again!
2) Check you have the correct ActionMethodSelectorAttribute attribute ([HttpPost]) over your controller method and that your method name is spelt correctly.
3) Check that you have the correct path in your request.
4) Check you are sending the correct data to the controller!!!
5) Check that the method is public.
6) Check that you are authorised to access that controller/method.
7) Check that you don't have any duplicate method names with either, a) the same parameters and name (if your not using an ActionMethodSelectorAttribute, or b) the same names and method select attributes.
8) Remove all parameters from your method, put a breakpoint at the start of the method, and try making the request and see if it hits the breakpoint. If it works without parameters and not with, then you are not passing the correct required data into the method.
9) Make your request and check the response!! (example below):
// make your request
$http({
method: 'POST',
url: '/Controller/Method',
data: {
foo: bar
}
}).then(function(response) {
// check your response (if a success status code was resolved)
console.log(response);
}, function(error) {
// check your error response
console.log(error);
});
If you have a 404 then your method was not found, if you have a 500 then something blew up in your code, if you have a 401 then you are unauthorised etc... This is really useful to actually know what is going on with your request...
10) Check your application is running!

400 Bad request while sending restful request using angularJS

I am using angularJs and rest controllers for making web service call. I am getting 400 bad request. When I was making a request to change the status of the user then I am getting the error. Please find the below code for js file, controller and UI.
Js Controller-
var user=angular.module('userApp', ['ngAnimate']);
user.controller('userController',function($scope,$http){
var urlBase=window.location.pathname;
$scope.selection = [];
$scope.toggle=true;
$scope.statuses=['YES','NO'];
$scope.sortType= 'name'; // set the default sort type
$scope.sortReverse= false; // set the default sort order
$scope.searchUser= ''; // set the default search/filter term
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
//get all users and display initially
$http.get(urlBase+"/users")
.success(function(data){
$scope.users = data;
});
$scope.addUser = function addUser() {
if($scope.firstName=="" || $scope.lastName=="" || $scope.email == "" || $scope.mobile == ""|| $scope.status == ""){
alert("Insufficient Data! Please provide values for task name, description, priortiy and status");
}
else{
$http.post(urlBase + '/users/insert/' +$scope.firstName+'/'+$scope.lastName+'/'+$scope.email+'/'+$scope.mobile+'/'+$scope.status)
.success(function(data) {
$scope.users = data;
$scope.firstName="";
$scope.lastName="";
$scope.email="";
$scope.mobile="";
$scope.status="";
$scope.toggle='!toggle';
});
}
};
$scope.archiveUser = function archiveUser(id){
console.log(":: Value of id :"+id);
$http.post(urlBase+'users/archive/'+id)
.success(function(data) {
$scope.users = data;
console.log(":: Data updated and displayed.")
})
.failure(function(data){
alert("Failed to archieve task ::"+data);
});
};
});
A part in User interface where the code is being called , i am using ng-repeat for displaying values and then on click of button calling archiveUser(). Id value is coming fine.
<button class="btn" ng-Click='archiveUser(x.id)'><i class="fa fa-archive"></i></button>
Spring Controller for handling request-
#RequestMapping(value="users/archive/{userIds}",method = RequestMethod.POST,headers="Accept=application/json")
public List<User> archiveUser(#PathVariable int userId) {
User user = new User();
user=userService.getUserService(userId);
List<User> users=userService.getAllUserService();
return users;
}
The problem was with 's' as Paqman commented. I removed 's' and then save & tried, got the correct result that was expecting. Thanks Paqman.

console service response inside controller

i have written a service with take parameter on the basis of which it response me with the response of http request.
this.getPaymentDueDetails=function(date){
this.getfromRemote('paymentdue/'+btoa(date))
.success(function(response){
return response;
})
.error(function(response){
return false;
})
}
getfromRemote is my another service which make http request
now i am trying to get the response of this service call inside my controller function
$scope.callDueReports=function(blockNum){
var data;
data=myAngService.getPaymentDueDetails('2015-04-20');
console.log(data);
}
its quite obvious that i wont get any thing in data as the page loads initially but i want the result of getPaymentDueDetails int it.
Please modify your service to return the promise like below.
this.getPaymentDueDetails = function(date) {
return this.getfromRemote('paymentdue/' + btoa(date));
};
And in controller check if the promise is resolved.
$scope.callDueReports = function(blockNum) {
var data;
myAngService.getPaymentDueDetails('2015-04-20').then(function(dataFromService) {
data = dataFromService;
console.log(data);
})
.catch(function(response) {
console.error('error');
});
};

Uploading files using angualrjs and abp boilerplate with webapi

I am using ABP (ASP.NET Boilerplate) Web API and angularjs to build a SinglePageApplication. I already got it working to call the server side methods via angular and the abp framework. It is easy to just send JSON-data but I have no idea how to send files.
Here is an example of sending JSON-Data:
Server-Code
public class PostAppService : ApplicationService, IPostAppService
{
public LoginOutput Login(LoginInput input)
{
doSomeStuffHere();
}
}
[DependsOn(typeof(AbpWebApiModule))]
public class SimpleTaskSystemWebApiModule : AbpModule
{
public override void Initialize()
{
IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());
DynamicApiControllerBuilder
.ForAll<IApplicationService>(Assembly.GetAssembly(typeof(SimpleTaskSystemApplicationModule)), "tasksystem")
.Build();
}
}
Client-Code
(function() {
var app = angular.module('app');
var controllerId = 'sts.views.authentication.login';
app.controller(controllerId, [
'$scope', '$location', 'abp.services.tasksystem.authentication',
function ($scope, $location, authService) {
var vm = this;
vm.user = {
username: '',
password: ''
};
var localize = abp.localization.getSource('SimpleTaskSystem');
vm.login = function () {
abp.ui.setBusy(
null,
authService.login(
vm.user
).success(function(response) {
displayLoggedInMessage();
})
);
};
}
]);
})();
I would like to do something like this but instead of sending JSON-Data I would like to send an image selected via:
<input type="file"/>
Any ideas?
A good way of achieving upload file:
Create a controller named UploadController from the base
AbpController
Add a method to upload the file. Let's name it ProductPhoto
public JsonResult ProductPhoto(string comment, int productId)
{
try
{
if (!Request.Files.Any() || Request.Files[0] == null)
{
return null;
}
var fileName = Guid.NewGuid();
var uniqueFilePath = #"~\Upload\ProductPhotos\" + fileName;
Request.Files[0].SaveAs(uniqueFilePath);
//save your additional parameters such as comment, productId
return Json(new
{
Success = true,
FileName = fileName
});
}
catch (Exception ex)
{
Logger.Error(ex.ToString);
return Json(new
{
Success = false
});
}
}
On the client send send the file using jquery or angular
vm.showProductPhotoUploadFileDialog = function () {
var formData = = new FormData()
formData .append("productId", vm.form.product.id);
formData .append("formId", vm.form.id);
if (vm.newProductPhoto.comment) {
formData .append("comment", vm.newProductPhoto.comment);
}
$('#productPhotoFileInput').click();
};
After upload completes get the result using callback
vm.productPhotoUploaded = function (response) {
if (!response.success) {
return;
}
vm.productPhotoFileName = response.fileName;
};
At this step you have the unique filename generated on the server for this file. Now you can update your client side object. Or you can go on your cascade savings.
Note: One disadvantage of this approach is; when user uploads file and then cancels the master entity save, you have to manually handle to delete the temp file uploaded to server.

400 Bad Request when accessing a Sprint Rest method with AngularJs

I am trying to access an update rest method with AngularJs, but it is giving me 400 bad request error.
Here is my code.
#RestController
#RequestMapping("/api/loggedInUser")
public class UserController {
#RequestMapping(value = "/{id}",method = RequestMethod.PUT)
public AppUser updateLoggedInUser(#RequestBody AppUser user){
return userService.updateAppUser(user);
}
}
Here is the code for accessing the service from AngularJs:
App.factory('LoggedInUserService', ['$resource', function($resource) {
console.log('service injected');
return {
getLoggedInUser: $resource('api/loggedInUser', {}, {
query: {method: 'GET'}
}),
updateLoggedInUser: $resource('api/loggedInUser/:id', {}, {
update: {method: 'PUT', params: {id: '#id'}}
})
};
}]);
Here is the code for accessing the service in my app.js file.
.run(function($location, $rootScope, LoggedInUserService) {
LoggedInUserService.getLoggedInUser.query(function(loggedInUser) {
$rootScope.loggedInUser = loggedInUser;
console.log($rootScope.loggedInUser.username);
if (loggedInUser.role[0].authority === 'ADMIN_ROLE' && loggedInUser.pristineAccess) {
$rootScope.loggedInUser.isAdmin = true;
$rootScope.pristineAccess = false;
LoggedInUserService.updateLoggedInUser.update($rootScope.loggedInUser);
$location.path('/admin');
} else {
$rootScope.loggedInUser.isAdmin = false;
$location.path('/dashboard');
}
});
});
When I remove the #RequestBody annotation I don't get a 400 error but the parameter doesn't get populated.
What am I doing wrong here? I used the same kind of code in another place in the same application and it worked fine. The only difference here is that the rest method argument parameter is an entity object and not a pojo.
add consumes = MediaType.APPLICATION_JSON_VALUE to your controller method and check your POST content with web developers tool or firebug or simmilar tool
#RequestMapping(value = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE,method = RequestMethod.PUT)
public AppUser updateLoggedInUser(#RequestBody AppUser user){
return userService.updateAppUser(user);
}

Resources