简体   繁体   中英

Angular $http post not working with asp.net mvc sending null data

I'm Stuck with calling C# web API from angular $http post method as below.

My JSON Object is as below

var requestParams = {
    "CostObjects": $scope.costObjForSaveArray,
    "CostObjectHierarchies": $scope.costObjHierarchyForSaveArray,
};

API Call with Angular is as below

$http({
    method: "POST",
    url: API_ROOT + "BusinessDimension/UpdateCostObjects",
    data: requestParams,
    headers: {
        "Content-Type": "application/json"
    }
})

Now the API written in .NET is as below.

[HttpPost, ActionName("UpdateCostObjects")]
public HttpResponseMessage UpdateCostObjects([FromBody] JsonData data)
{
    var costObjects = JsonConvert.DeserializeObject<List<CostObjectM>>(data.Data);

    if (ModelState.IsValid)
    {
        var updatedCostObjects = Acornpadomainservice.UpdateCostObjects(costObjects).ToList();
        return Request.CreateResponse(updatedCostObjects);
    }
    else
    {
        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
    }
}

JSON class is as below

public class JsonData
{
   public string Data { get; set; }
}

Could anyone correct me what's I'm doing wrong?

Replace your post method parameter type to object or string in replace of JsonData and check if it's working or not..

Eg.

 [HttpPost, ActionName("UpdateCostObjects")]
    public HttpResponseMessage UpdateCostObjects([FromBody] object data)
    {
        var costObjects = JsonConvert.DeserializeObject<List<CostObjectM>>(data.Data);

        if (ModelState.IsValid)
        {
            var updatedCostObjects = Acornpadomainservice.UpdateCostObjects(costObjects).ToList();
            return Request.CreateResponse(updatedCostObjects);
        }
        else
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
        }
    }
$http({
  method: "POST",
  url: API_ROOT + "BusinessDimension/UpdateCostObjects",
  data:  JSON.stringify(requestParams),
  contentType: 'application/json; charset=utf-8'
})

Edit the following code

 $http({ method: "POST", url: API_ROOT + "BusinessDimension/UpdateCostObjects", data: {Data :angular.toJson(requestParams)}, headers: { "Content-Type": "application/json" } }) 

The angular.toJson(data) will stringfy you object because the Json object is expecting a string type on a Data field to be sent to it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM