How to POST object + array to WebApi .NET/C# controller using AngularJS $http?

911 views Asked by At

My C# model:

public class MyModel
{
    public string MyString { get; set; }
    public int MyInt { get; set; }
    public List<MyList> MyList { get; set; }
}

public class MyList
{
    public string MyListString { get; set; }
    public int MyListInt { get; set; }
}

My C# method:

[HttpPost]
public void SomeMethod(MyModel MyModel)
{

My AngularJS $http:

$http({
    url: "/api/SomeCtrl/SomeMethod",
    method: "POST",
    data: // WHAT TO PUT HERE?
    headers: { 'Content-Type': 'application/json' }
});

I'm able to fill MyModel with:

data: transportDocumentData.TDShipment,

Or MyList which is present in MyModel with:

data: JSON.stringify({ Package: transportDocumentData.TDShipment.packageData }),

But I don't know how to fill them both. I tried with both options:

$http({
    url: "/api/SomeCtrl/SomeMethod",
    method: "POST",
    data: myModelData.MyModel,
    data: JSON.stringify({ MyList: myModelData.MyModel.myListData }),
    headers: { 'Content-Type': 'application/json' }
});

Which won't work, because the second data overwrites the first one. I also tried this:

var abc = myModelData.MyModel;
$http({
    url: "/api/SomeCtrl/SomeMethod",
    method: "POST",
    data: JSON.stringify({ MyList: myModelData.MyModel.myListData }), abc
    headers: { 'Content-Type': 'application/json' }
});

But in this case only the MyList is filled.

I tried to modify MyMethod like this:

[HttpPost]
public void SomeMethod(List<MyModel> MyModel)
{

With even worse results.

So, how is it done correctly?

EDIT: I forgot to include these:

$scope.myListData = [{ myListString: "bar", myListInt: 5 }];

$scope.myData = {
    myString: "foo",
    myInt: 3,
    myListData: $scope.myListData
}

 var myModelData = {
    MyModel: $scope.myData
};
1

There are 1 answers

8
Lukasz Mk On

You need just create a JSON object, will match your C# model and send it - that's all. WebApi will do the job (Model binding).

So answering your question:

data: // WHAT TO PUT HERE?

create/fill your json model in Angular:

$scope.myListData = [{ myListString: "bar", myListInt: 5 }];

$scope.myData = {
    myString: "foo",
    myInt: 3,
    myListData: $scope.myListData
};

and pass it trough directly:

$http({
    url: "/api/SomeCtrl/SomeMethod",
    method: "POST",
    data: $scope.myData
});


Is that answer on your question?