首页 > 代码库 > MVC4 WebApi

MVC4 WebApi

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using testWebApi.Models;

namespace testWebApi.Controllers
{
    public class ValuesController : ApiController
    {
        // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/values 一般用作添加
        public UserInfo Post([FromBody]UserInfo userInfo)
        {
            userInfo.Age += 1;
            return userInfo;
        }

        // PUT api/values/5 一般用作修改
        public UserInfo Put(int id, UserInfo userInfo)
        {
            userInfo.Age -= 1;
            return userInfo;
        }

        // DELETE api/values/5
        public int Delete(int id)
        {
            return id + 1;
        }
    }
}
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>TestApi</title>
    <script src="http://www.mamicode.com/~/Scripts/jquery-1.8.2.js"></script>
    <script type="text/javascript">
        $(function () {
            //$("#btnPost").click(function () {
            //    DoPost();
            //});
            //$("#btnPut").click(function () {
            //    DoPut();
            //});
            $("#btnDelete").click(function () {
                DoDelete();
            });
        });
        function DoPost()
        {
            $.ajax({
                type: "POST",
                url: "/api/values",
                data: { "Id": 1, "UserName": "chm", "Age": 1 },
                success:function(data){
                    alert(data.Id + " " + data.UserName + " " + data.Age);
                }
            });
        }
        function DoPut() {
            $.ajax({
                type: "PUT",
                url: "/api/values/1",
                data: { "Id": 1, "UserName": "chm", "Age": 1 },
                success: function (data) {
                    alert(data.Id + " " + data.UserName + " " + data.Age);
                }
            });
        }

        function DoDelete() {
            $.ajax({
                type: "DELETE",
                url: "/api/values/1",
                data: { },
                success: function (data) {
                    alert(data);
                }
            });
        }
    </script>
</head>
<body>
    <div>
        <input type="button" id="btnPost" value="http://www.mamicode.com/post"/>
        <br/>
        <input type="button" id="btnPut" value="http://www.mamicode.com/put"/>
        <br />
        <input type="button" id="btnDelete" value="http://www.mamicode.com/delete" />
    </div>
</body>
</html>

  

MVC4 WebApi