WebApi的调用-1.前端调用

2017-09-22  本文已影响0人  大捕猎店

前端调用

前端

html

<div class="row">
    <form id="queryForm">
        <input name="id" type="text" />
        <input name="name" type="text" />
    </form>
</div>

<div class="row">
    <div class="panel panel-warning">
        <div class="panel-heading">Get</div>
        <div class="panel-body">
            <a class="btn btn-primary" id="btn1">无参</a>
            <a class="btn btn-primary" id="btn2">1个参数</a>
            <a class="btn btn-primary" id="btn3">2个参数</a>
            <a class="btn btn-primary" id="btn4">实体参数1 <span class="label label-warning">[FromUri]</span></a>
            <a class="btn btn-primary" id="btn5">实体参数2 <span class="label label-warning">(传递反序列化){ 参数: JSON.stringify(json) }</span></a>
        </div>
    </div>
    <div class="panel panel-success">
        <div class="panel-heading">post</div>
        <div class="panel-body">
            <p>
                <div>
                    <input name="postsubmit" type="text"/>
                </div>
            </p>
            <p>
                <a class="btn btn-success" id="postbtn1">
                    1个参数
                    <span class="label label-danger">key为空</span>
                </a>
                <a class="btn btn-success" id="postbtn2">
                    1个json
                    <span class="label label-danger">(传递序列化)传递:JSON.stringify({ id: 1, pass: '123', name: "tangsansan" }),接收:实体,</span>
                    <span class="label label-warning">contentType: 'application/json'</span>
                </a>
            </p>
            <p>
                <a class="btn btn-success" id="postbtn5">
                    1个表单
                    <span class="label label-danger">(传递序列化)传递:JSON.stringify($('#queryForm').serialize()),接收:dynamic,</span>
                    <span class="label label-warning">contentType: 'application/json'</span>
                </a>
                <a class="btn btn-success" id="postbtn6">
                    1个表单
                    <span class="label label-danger">传递:$('#queryForm').serialize(),接收:实体</span>
                </a>
            </p>
            <p>
                <a class="btn btn-success" id="postbtn7">
                    1个复杂json
                    <span class="label label-danger">(传递序列化)传递:{ "User": "{ id: 1, pass: '123', name: "tangsansan" }", "Info": "info" },接收:JObject</span>
                </a>
            </p>
        </div>
    </div>
</div>

js

<script>
    var $queryform = { id: 1, pass: '123', name: "tangsansan" }

    $(function () {
        //get传递无参
        $('#btn1').on('click', function () {
            $.ajax({
                url: 'http://localhost:809/api/Values/GetList',
                type: 'get',
                success: function (data) {
                    alert(data)
                }
            });
        });
        //get传递1个参数
        $('#btn2').on('click', function () {
            $.ajax({
                url: 'http://localhost:809/api/Values/Get',
                type: 'get',
                data: { id: 1 },
                success: function (data) {
                    alert(data)
                }
            });
        });
        //get传递2个参数
        $('#btn3').on('click', function () {
            $.ajax({
                url: 'http://localhost:809/api/Values/GetList',
                type: 'get',
                data: { id: 1, pass: 'aa' },
                success: function (data) {
                    alert(data)
                }
            });
        });

        //get传递实体1 [fromurl]
        $('#btn4').on('click', function () {
            $.ajax({
                url: 'http://localhost:809/api/Values/GetUserList',
                type: 'get',
                data: $queryform,
                success: function (data) {
                    alert(data)
                }
            });
        });

        //get传递实体2 JSON.stringify字符串
        $('#btn5').on('click', function () {
            $.ajax({
                url: 'http://localhost:809/api/Values/UserJsonList',
                type: 'get',
                data: { userJson: JSON.stringify($queryform) },
                success: function (data) {
                    alert(data)
                }
            });
        });
        
        //post传递一个参数
        $('#postbtn1').on('click', function () {
            var $posttext = $('input[name=postsubmit]').val();
            $.ajax({
                url: 'http://localhost:809/api/Values/PostOne',
                type: 'post',
                //data: { "value": $posttext }, //key=value,但后台接收为空
                data: { "": $posttext },  //key为空
                success: function (data) {
                    alert(data);
                }
            });
        });

        //post传递json字符串
        $('#postbtn2').on('click', function () {
            $.ajax({
                url: 'http://localhost:809/api/Values/PostTwoForm',
                type: 'post',
                contentType: 'application/json',     //必须加上,声明为json
                data: JSON.stringify($queryform),    
                success: function (data) {
                    alert(data);
                }
            });
        });

        //post传递一个表单
        //通过dynamic动态类型能顺利得到多个参数,省掉了[FromBody]这个累赘,
        //并且ajax参数的传递不用使用"无厘头"的{"":"value"}这种写法,
        //有一点需要注意的是这里在ajax的请求里面需要加上参数类型为Json,即 contentType: 'application/json', 这个属性。
        $('#postbtn5').on('click', function () {
            $.ajax({
                url: 'http://localhost:809/api/Values/PostOneForm',
                type: 'post',
                contentType: 'application/json',     //必须加上,声明为json
                 data: JSON.stringify($('#queryForm').serialize()),
                 success: function (data) {
                    alert(data);
                }
            });
        });
        
        //post传递一个表单
        $('#postbtn6').on('click', function () {
            $.ajax({
                url: 'http://localhost:809/api/Values/PostTwoForm',
                type: 'post',
                data: $('#queryForm').serialize(),
                success: function (data) {
                    alert(data);
                }
            });
        });

        //post传递复杂json字符串
        $('#postbtn7').on('click', function () {
            $.ajax({
                url: 'http://localhost:809/api/Values/PostThreeeForm',
                type: 'post',
                data: { "User": $queryform, "Info": "info" },
                success: function (data) {
                    alert(data);
                }
            });
        });

    });
</script>

后台

public class ValuesController : ApiController
    {
        [HttpGet]
        public IEnumerable<string> GetList()
        {
            return new string[] { "value1", "value2" };
        }

        [HttpGet]
        public string Get(int id)
        {
            return "value";
        }

        [HttpGet]
        public IEnumerable<string> GetList(int id, string pass)
        {
            return new string[] { id.ToString(), pass.ToString() };
        }

        //Get传参:实体,必须添加 FromUri
        [HttpGet]
        public string GetUserList([FromUri]User user)
        {
            return string.Format("id:{0},name:{1},pass:{2}", user.id.ToString(), user.name, user.pass);
        }

        [HttpGet]
        public string UserJsonList(string userJson)
        {
            User user = JsonConvert.DeserializeObject<User>(userJson);
            return string.Format("id:{0},name:{1},pass:{2}", user.id.ToString(), user.name, user.pass);
        }

        // POST api/values
        [HttpPost]
        public string PostOne([FromBody]string value)
        {
            return value;
        }

        //一个表单(一个json)
        [HttpPost]
        public string PostOneForm(dynamic value)
        {
            string user = Convert.ToString(value);
            return user;
        }

        //一个表单(一个实体)
        [HttpPost]
        public string PostTwoForm(User user)
        {
            //Dictionary<string, object> objects = GetRequest();

            return string.Format("id:{0},name:{1},pass:{2}", user.id.ToString(), user.name, user.pass);
        }

        [HttpPost]
        public string PostThreeeForm(JObject jObject)
        {
            //Dictionary<string, object> objects = GetRequest();
            string username = HttpContext.Current.Request.Form["User[name]"];
            dynamic json = jObject;
            JObject User = json.User;
            User user = User.ToObject<User>();
            //Dictionary<string, object> objects = GetRequest();

            return string.Format("id:{0},name:{1},pass:{2}", user.id.ToString(), user.name, user.pass);
        }

        // PUT api/values/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        public void Delete(int id)
        {
        }

        /// <summary>
        /// 获取所有参数   
        /// </summary>
        /// <returns>
        ///     A System.Collections.Generic.Dictionary<string,object> value...
        /// </returns>
        public Dictionary<string, object> GetRequest()
        {
            var getrequest = HttpContext.Current.Request.Form;
            Dictionary<string, object> dict = new Dictionary<string, object>();

            for (int i = 0; i < getrequest.AllKeys.Length; i++)
            {
                dict.Add(getrequest.GetKey(i), getrequest[i]);
            }
            return dict;
        }
    }
上一篇下一篇

猜你喜欢

热点阅读