dev53
dev53

Reputation: 414

Posting AngularJS JSON Array ASP.NET Web API Error

This seems like to be a common problem and I have researched and tried just about everything I could find on the web today and I am still not getting my post to work. Using developer tools with chrome I am able to view the request payload and it contains the data I am trying to post but then I get the error

"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'CertAngular.cert_unit_Angular' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array. Path '', line 1, position 1."

The Request Payload that the header in developer tools contains is

[{"cc_id":7778,"unit_id":"TEST1","$$hashKey":"object:5"}]

I have tried just about everything that I can find to get this to work but I am still struggling. I am assuming it is something simple that I am overlooking or not quite understanding

The code for my HTTP post in AngularJS is done like this after I add some data to the availableclients...

$scope.availableclients = [];


$scope.submitCertData = function () {

    var objdata = JSON.stringify($scope.availableclients);

    $http.post('api/PostAttempt2/Postcert_unit_Angular/', objdata)
    .success(function () {

        console.log("Posted");
    })

}

I am using the template post controller for "Web API 2 Controller with actions, using Entity Framework" The code for that is as follows... (I left it how Visual Studio created it other than adding [FromBody] and trying a combination of things other people had suggested.)

// POST: api/PostAttempt2
[ResponseType(typeof(cert_unit_Angular))]
public IHttpActionResult Postcert_unit_Angular([FromBody]cert_unit_Angular cert_unit_Angular)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.cert_unit_Angular.Add(cert_unit_Angular);

        try
        {
            db.SaveChanges();
        }
        catch (DbUpdateException)
        {
            if (cert_unit_AngularExists(cert_unit_Angular.unit_id))
            {
                return Conflict();
            }
            else
            {
                throw;
            }
        }

        return CreatedAtRoute("DefaultApi", new { id = cert_unit_Angular.unit_id }, cert_unit_Angular);
    }

My WebApi Route Config is...

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

        config.Routes.MapHttpRoute(
            name: "DefaultAPI",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }

Any help is appreciated and I can provide whatever information is necessary. Thanks.

Here is the cert_unit_Angular class. Sorry I missed that.

     public class cert_unit_Angular
    {
        public string unit_id { get; set; }
        public Int32 cc_id { get; set; }
    }

Upvotes: 0

Views: 1104

Answers (1)

Dan Kuida
Dan Kuida

Reputation: 1057

your web api expects something of this kind {"unit_id":"ncn","cc_id":5} what you need is that it would be an array

so define something like this as method signature

public IHttpActionResult Postcert_unit_Angular([FromBody]List<cert_unit_Angular> unitID)

or

public IHttpActionResult Postcert_unit_Angular([FromBody]cert_unit_Angular[] unitID)

Upvotes: 1

Related Questions