【问题标题】:angularjs Pass data has list dataangularjs 传数据有列表数据
【发布时间】:2017-09-12 07:27:30
【问题描述】:

我想传递数据,这里有孩子的列表

{
 id : 1,
 title : 'test',
 childs : [
    { id : 1, name: 'name1' },
    { id : 2, name: 'name2' },
    { id : 3, name: 'name3' }]
}

我希望它传递给 web api 控制器

public IHttpActionResult Post(Batche model){
     return model;
}

和批处理

 public class Batche
 {
     public long Id { get; set; }
     public string title{ get; set; }
     public ICollection<BatchDetail.BatchDetail> BatchDetails { get; set; }
 }

和批次详情

public class BatchDetails(){
      public long Id { get; set; }
      public string Name{ get; set; }
}

当我发布数据时让我为空

$http({
   method : 'POST',
   url : baseUrl + "api/MyController",
   data : $scope.model
})

【问题讨论】:

    标签: c# angularjs asp.net-web-api pass-data


    【解决方案1】:

    在方法参数前使用[FromBody]

    public IHttpActionResult Post([FromBody]Batche model){
    

    【讨论】:

    • @HadiJahangiri 你可以试试data : JSON.stringify($scope.model)
    【解决方案2】:

    您可以使用工厂和控制器将数据从客户端传递到服务器端(例如 web api 控制器或 mvc 控制器)。例如,您可以创建角度工厂:

    myApp.factory('MyService', function ($http, $q)) {
       var _postMethod = function (object) {
        var deferred = $q.defer();
        $http.post("/api/ControllerName/", object).then(function (result) {
            deferred.resolve(result.data);
        },
        function () {
            deferred.reject();
        });
        return deferred.promise;
    }
    }
    return {
        postMethod: _postMethod
    }
    })
    

    然后,创建角度控制器:

    myApp.controller('MyController', function ($scope, $routeParams, $rootScope, MyService) {
    $scope.array = [];
     $scope.myPostMethod = function (object) {
        $scope.object= object;
        MyService.postMethod(object).then(function (data) {
            object.Id = data;
            $scope.array.push(object);
            $scope.array= {};
            $scope.form.$setPristine();
        }, function () { });
    }
     )}
    

    在 wep api 控制器中,您可以像这样创建函数:

    // POST: api/ControllerName
        [HttpPost]
        public void Post([FromBody]Models.YourModel value)
        {
            try
            {
                //your code
            }
            catch (Exception ex)
            {
                throw;
            }
        }
    

    如果您有更多问题,请写...快乐编码...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多