how to post objects from angular to a webapi controller

1.6k Views Asked by At

I am creating a pdf using pdfsharp. I need to pass the chart legend data(name,color) to the pdfsharp controller. I am using a angular $http post, a ajax post would be fine as well. the error I am getting is

Request URL:http://localhost:46691/api/exportChartPdf/[object%20Object],[object%20Object],[object%20Object],[object%20Object],[object%20Object],[object%20Object],[object%20Object],[object%20Object],[object%20Object],[object%20Object],[object%20Object],[object%20Object],[object%20Object],[object%20Object],[object%20Object],[object%20Object]

do i need to some how pass it as a string? if so how would I parse it in the api controller back to the way I need it?

the objects i am trying to pass back

0: Object
     color: "rgb(67,134,215)"
     name: "Fleming Place - Miscellaneous Spec Builders"
__proto__: Object
1: Object
2: Object
3: Object
4: Object

javascript

 var legendModel = $scope.seriesData.map(function (a) {
            return {
                color: a.color,
                name: a.name
            };
        });
        $http.post('/api/exportChartPdf/' + legendModel);

api controller

 [HttpPost]
    public PDF Post() // allow nullable parameter
    {

        try
        {
2

There are 2 best solutions below

0
On BEST ANSWER

You should be posting the object on the form body, not on the querystring. In addition, your Web API controller should receive a strongly typed object that mirrors the data that you're passing.

public class Data
{
    public string Color { get; set; }
    public string Name { get; set; }
}

[HttpPost]
public PDF Post([FromBody]List<Data> data) 
{
    ... 
}

And then simply post the object.

var legendModel = $scope.seriesData.map(function (a) {
        return {
            color: a.color,
            name: a.name
        };
    });

$http.post('/api/exportChartPdf/', legendModel);
0
On

Looks like your controller action is missing parameter on it,

[HttpPost]
public PDF Post(SomeClass legendModel) // allow nullable parameter
{

    try
    {

SomeClass would contain color & name properties. Then you should correct your $http.post call, pass 2nd param as data in JSON format.

$http.post('/api/exportChartPdf', { legendModel: legendModel);