WebapI POST参数设置

一,传递数组,

(1)后台代码

        [HttpPost]
        public bool SaveData(string[] ids)
        {
            return true;
        }

(2)前端调用代码

var arr = ["1", "2", "3", "4"];
    $.ajax({
        type: "post",
        url: "http://localhost:27221/api/Charging/SaveData",
        contentType: 'application/json',
        data: JSON.stringify(arr),
        success: function (data, status) { }
    });

          注意:后台直接用数组参数接收即可,前端需要用JSON.stringify()将数组字符串化。同时contentType类型应为 'application/json'

 

二,传递基础类型

  (1)后台代码 

        [HttpPost]
        public object SaveData(dynamic obj)
        {
            var strName = Convert.ToString(obj.NAME);
            return strName;
        }

       (2)前端代码

 $.ajax({
        type: "post",
        url: "http://localhost:27221/api/Charging/SaveData",
        contentType: 'application/json',
        data: JSON.stringify({ NAME: "Jim",DES:"备注" }),
        success: function (data, status) {}
    });

      注意:传递基础类型值时候,后台使用dynamic,前端使用JSON.stringify({ NAME: "Jim",DES:"备注" })处理,同时contentType类型应为 'application/json'

 

三,参数为实体类型

  (1)后台代码

       [HttpPost]
        public bool SaveData(TB_CHARGING oData)
        {
            return true;
        }

       (2)前端代码

 $.ajax({
        type: "post",
        url: "http://localhost:27221/api/Charging/SaveData",
        data: { ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" },
        success: function (data, status) {}
    });

    注意:参数为实体类型的时候,正常使用,但同时contentType类型不能为 'application/json'

        另一种方式也可以,如下所示:

  var postdata = { ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" };
    $.ajax({
        type: "post",
        url: "http://localhost:27221/api/Charging/SaveData",
        contentType: 'application/json',
        data: JSON.stringify(postdata),
        success: function (data, status) {}
    });

        [HttpPost]
        public bool SaveData(TB_CHARGING lstCharging)
        {
            return true;
        }

 

四 实体类型和基础类型同时使用

         此时可以使用dynamic

       [HttpPost]
        public object SaveData(dynamic obj)
        {
            var strName = Convert.ToString(obj.NAME);
            var oCharging = Newtonsoft.Json.JsonConvert.DeserializeObject<TB_CHARGING>(Convert.ToString(obj.Charging));
            return strName;
        }
 var postdata = { ID: "1", NAME: "Jim", CREATETIME: "1988-09-11" };
    $.ajax({
        type: "post",
        url: "http://localhost:27221/api/Charging/SaveData",
        contentType: 'application/json',
        data: JSON.stringify({ NAME:"Lilei", Charging:postdata }),
        success: function (data, status) {}
    });

 

posted @ 2018-08-08 17:24  辣根弟弟  阅读(1553)  评论(0编辑  收藏  举报