0

I'm having an issue posting data to my controller using angularjs.

The data looks good while debugging, right until it hits my controller and then the arguments being passed in are always null.

public class NewCompArgs { public string Name { get; set; } public string Description { get; set; } } //Tested with [HttpPost] here, and it didn't work // Tested using [FromBody]NewCompArgs args, and splitting // out into Name and Decription strings with [FromBody] public ActionResult AddNewComponent(NewCompArgs args) { Component NewComp = new Component { Name = args.Name, Description = args.Description }; _context.Add(NewComp); _context.SaveChanges(); return Json(NewComp); } 

NewCompArgs args is null every time.

Here is the service I use to hit my controller:

app.factory('Components', function ($http, $q) { var service = {}; service.AddNewComponent = function (args) { var deferred = $q.defer(); $http.post('/Components/AddNewComponent', { args: args }).then(function (response) { deferred.resolve(response.data); }); return deferred.promise; }; return service; }); 

Here is the angular controller function:

$scope.newComponent = function () { Components.AddNewComponent($scope.compArgs).then(function (response) { }); } 

Just an example of the data I'm getting during debugging

Angular Controller: ng controller

Angular Service: ng service

MVC Controller: MVC Controller

Any advice is greatly appreciated!

4
  • You're passing { args: args } but the server is expecting an object which contains name and description, not args. Commented Apr 6, 2018 at 6:34
  • Did you try to hit this method using PostMan API client? is it working there properly? Commented Apr 6, 2018 at 6:34
  • Possible duplicate of AngularJS - $http.post send data as json Commented Apr 6, 2018 at 6:35
  • 1
    @osm0sis You are returning ActionResult - it's wrong. I think you are extending Controller instead of ApiController. Commented Apr 6, 2018 at 6:41

1 Answer 1

1

I'm not sure if this can help, but in Angular 2/5 when u want to trigger an method in a controller you can use method().subscribe(); maybe this will help you.

Sign up to request clarification or add additional context in comments.

2 Comments

He's using angularjs.
I know, that's the reason I'm not sure if it's help but he should try.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.