【问题标题】:Controller receives Null arguments from angularjs service post控制器从 angularjs 服务帖子接收 Null 参数
【发布时间】:2018-09-16 02:49:04
【问题描述】:

我在使用 angularjs 将数据发布到我的控制器时遇到问题。

调试时数据看起来不错,直到它到达我的控制器,然后传入的参数始终为空。

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 每次都为空。

这是我用来点击我的控制器的服务:

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

这里是角度控制器功能:

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

只是我在调试期间获得的数据的一个示例

角度控制器: ng controller

角度服务: ng service

MVC 控制器: MVC Controller

非常感谢任何建议!

【问题讨论】:

  • 您正在传递{ args: args },但服务器需要一个包含namedescription 的对象,而不是args
  • 您是否尝试使用PostMan API 客户端来实现此方法?它在那里工作正常吗?
  • @osm0sis 你正在返回ActionResult - 这是错误的。我认为您正在扩展 Controller 而不是 ApiController

标签: c# .net angularjs model-view-controller


【解决方案1】:

我不确定这是否有帮助,但在 Angular 2/5 中,当你想触发控制器中的方法时,你可以使用 method().subscribe();也许这会对你有所帮助。

【讨论】:

  • 他正在使用 angularjs。
  • 我知道,这就是我不确定是否有帮助但他应该尝试的原因。
猜你喜欢
  • 2019-07-21
  • 2014-11-10
  • 2018-05-01
  • 1970-01-01
  • 2014-01-04
  • 1970-01-01
  • 1970-01-01
  • 2017-02-09
  • 1970-01-01
相关资源
最近更新 更多