angularjs Pass data has list data

1.4k views Asked by At

I want to pass data what has list of child like here

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

I want it pass to web api controller

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

and batch

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

and batch details

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

when I post data get me null

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

There are 2 answers

0
oknevermind On

You can use factory and controller for pass data from client to server side (etc. web api controller or mvc controller). For example, you can create angular factory:

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

And, create angular controller:

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

In wep api controller you can create function just like that:

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

If you have more questions, please write... Happy coding...

1
Pankaj Parkar On

Use [FromBody] before your method parameter

public IHttpActionResult Post([FromBody]Batche model){