如何通过angular $ http.get将json数据发送到webapi

时间:2015-09-07 10:14:04

标签: c# json angularjs asp.net-web-api2

WebAPI代码

 [HttpPost]
        public IHttpActionResult PostData(ARParameter allParams)
        {
               //My Code
        }

  public class ARParameter 
        {
            public string action;
            public SomeRules rule;
        }

 public class SomeRules 
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string PassFail { get; set; }
    }

我想调用PostData方法

我的javascript代码是

 addData=function ($scope) {
            var data=
            +'{'
            +'    "action":"post",'
            +'    "rule":"{}"'
            +'}';


            $http({
                url: urlContent + '/api/Rules',
                method: "POST",
                params: { allParams: data }
            }).success(function (response) {
                $scope.rules = response;
            });;
        }

如何构建json?

2 个答案:

答案 0 :(得分:0)

服务器端更改

  • 在您的操作中设置ActionName属性。

    [ActionName("PostData")]
    [HttpPost]
    public IHttpActionResult PostData(ARParameter allParams)
    {
           //My Code
    }
    

客户端更改

  • Json格式看起来像

var data= {"action":"post","rule":{"ID":"1","Name":"Ramesh","PassFail":"Pass"}}

  • 您的客户端代码应该看起来像

    $scope.addData = function () { var data= {"action":"post","rule":{"ID":"1","Name":"Ramesh","PassFail":"Pass"}} $http({ url: urlContent + '/api/Rules/PostData', method: "POST", data: data }).success(function (response) { $scope.rules = response; });; }

答案 1 :(得分:0)

您的API方法PostData的类型为POST,因此调用应为POST。下面是构建json的方法。

var data={"action":"post","rule":{"ID":"123","Name":"namehere","PassFail":"passfailhere"}}