MVC增删改查整套(ajax,两个项目跨域)


///API
namespace WebApplication1.Controllers
{
     [EnableCors("*", "*", "*")]
    public class BookApiController : ApiController
    {
        
        day19_BookManagerEntities book = new day19_BookManagerEntities();
        
        // GET: api/BookApi
        public IEnumerable<Book> Get()
        {
            return book.Book;
        }
        [HttpGet]
        public List<Book> Get(int id)
        {
            return book.Book.Where(T => T.Book_ID==id).ToList();
        }
        // GET: api/BookApi/5
        public IEnumerable<Book> GetName(string id)
        {
            return book.Book.Where(T => T.Book_Name.Contains(id)).ToList();
        }

        // POST: api/BookApi
        public void Post([FromBody]Book value)
        {
            book.Book.Add(value);
            book.SaveChanges();
        }

        // PUT: api/BookApi/5
        public void Put(int id, [FromBody]Book value)
        {
            var b = book.Book.Where(T => T.Book_ID == id).FirstOrDefault();
            if (b != null)
            {
                b.Book_ID = value.Book_ID;
                b.Book_Name = value.Book_Name;
                b.Book_Num = value.Book_Num;
                b.Book_Price = value.Book_Price;
            }
            book.SaveChanges();
        }

        // DELETE: api/BookApi/5
        public HttpResponseMessage Delete(int id)
        {
            var b = book.Book.Where(T => T.Book_ID == id).FirstOrDefault();
            try
            {
                if (b != null)
                {
                    book.Book.Remove(b);
                    book.SaveChanges();
                    return new HttpResponseMessage() { StatusCode = HttpStatusCode.OK };
                }
                else
                {
                    return new HttpResponseMessage() { StatusCode = HttpStatusCode.NoContent };
                }
            }
            catch (Exception)
            {
                return new HttpResponseMessage() { StatusCode = HttpStatusCode.InternalServerError };
            }
        }
    }
}



    

///路由WebApiconfing(切记改路由,在Api里做修改)
     public static void Register(HttpConfiguration config)
        {
            config.EnableCors();
            // Web API 配置和服务

            // Web API 路由
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            config.Routes.MapHttpRoute(
             name: "ActionApi",
             routeTemplate: "Actionapi/{controller}/{action}/{id}",
             defaults: new { id = RouteParameter.Optional }
         );
        }




显示页面
<body>
    <div>
        <a href="/BookAction/Add">添加</a>
        <input type="text" id="txtname" placeholder="请输入书名"  />
        <a href="#" οnclick="Select()">查询</a>
        <table>
            <tr>
                <td>书名</td>
                <td>数量</td>
                <td>价格</td>
                <td>删除</td>
            </tr>
            <tbody id="tbody1">

            </tbody>
        </table>

    </div>

    <script>
        $.ready(Show());
        function Show() {
            $.ajax({
                url: "http://localhost:57173/api/BookApi",
                type: "Get",
                success: function (data) {
                    var str = "";
                    for (var i = 0; i < data.length; i++) {
                        str += "<tr>";
                        str += "<td>" + data[i].Book_Name + "</td>"
                        str += "<td>" + data[i].Book_Num + "</td>"
                        str += "<td>" + data[i].Book_Price + "</td>"
                        str += "<td><input  type=\"button\" οnclick='Del(" + data[i].Book_ID + ")' value=\"删除\" /></td>"
                        str += "<td><input  type=\"button\" οnclick='Upt(" + data[i].Book_ID + ")' value=\"修改\" /></td>"
                        str += "</tr>";
                    }
                    $("#tbody1").html(str);
                }
            })
        }

        function Del(id) {
            $.ajax({
                url: "http://localhost:57173/api/BookApi/"+id,
                type: "Delete",
                success: function () {
                    alert("删除成功");
                    Show();
                }
            })
        }

        function Upt(id) {
            location.href = "/BookAction/Upt?id=" + id;
        }

        function Select() {
            var name = $("#txtname").val();
            if (name!="") {
                $.ajax({
                    url: "http://localhost:57173/Actionapi/BookApi/GetName/" + name,
                    type: "Get",
                    success: function (data) {
                        var str = "";
                        for (var i = 0; i < data.length; i++) {
                            str += "<tr>";
                            str += "<td>" + data[i].Book_Name + "</td>"
                            str += "<td>" + data[i].Book_Num + "</td>"
                            str += "<td>" + data[i].Book_Price + "</td>"
                            str += "<td><input  type=\"button\" οnclick='Del(" + data[i].Book_ID + ")' value=\"删除\" /></td>"
                            str += "<td><input  type=\"button\" οnclick='Upt(" + data[i].Book_ID + ")' value=\"修改\" /></td>"
                            str += "</tr>";
                        }
                        $("#tbody1").html(str);
                    }
                })
            }
            else {
                Show();
            }
            
        }

    </script>
</body>
</html>


///Add页面
<body>
    <div>
        <table>
            <tr>
                <td>书名</td>
                <td>
                    <input type="text" name="name" id="txtname" />
                </td>
            </tr>
            <tr>
                <td>数量</td>
                <td>
                    <input type="text" name="name" id="txtnum" />
                </td>
            </tr>
            <tr>
                <td>价格</td>
                <td>
                    <input type="text" name="name" id="txtprice"/>
                </td>
            </tr>
            <tr>
                <td></td>
                <td>
                    <input type="button"  name="name" value="提交"οnclick="Add()" />
                </td>
            </tr>
        </table>
    </div>
    <script>
        function Add() {
            $.ajax({
                    url: "http://localhost:57173/api/BookApi",
                    type: "Post",
                    dataType: "json",
                    data:{Book_Name:$("#txtname").val(),Book_Num:$("#txtnum").val(),Book_Price:$("#txtprice").val()},
                    success: function () {
                        alert("提交成功");
                        location.href = "/BookAction/Index";
                    }
            })
        }
    </script>
</body>
</html>

修改页面
<body>
    <div>
        <table>
            <tr>
                <td>书名</td>
                <td>
                    <input type="text" name="name" id="txtname" />
                </td>
            </tr>
            <tr>
                <td>数量</td>
                <td>
                    <input type="text" name="name" id="txtnum" />
                </td>
            </tr>
            <tr>
                <td>价格</td>
                <td>
                    <input type="text" name="name" id="txtprice" />
                </td>
            </tr>
            <tr>
                <td>
                    <input type="hidden" name="name" id="txtid" />
                </td>
                <td>
                    <input type="button" name="name" value="提交" οnclick="Upt()" />
                </td>
            </tr>
        </table>
    </div>
    <script>
        //$.ready(Show()
           
        //    );
        $(function () {
            Show();
        })
        function Show() {
            var id = location.search.split('=')[1];
            alert(id);
            $.ajax({
                url: "http://localhost:57173/Actionapi/BookApi/Get/"+id,
                type: "Get",
                success: function (data) {
                    for (var i = 0; i < data.length; i++) {
                        $("#txtid").val(data[i].Book_ID);
                        $("#txtname").val(data[i].Book_Name);
                        $("#txtnum").val(data[i].Book_Num);
                        $("#txtprice").val(data[i].Book_Price);
                    }
                }
            })
        }

        function Upt() {
            var id = location.search.split("=")[1];
            alert(id);
            $.ajax({
                url: "http://localhost:57173/api/BookApi/"+id,
                type: "Put",
                dataType: "json",
                data: { Book_Name: $("#txtname").val(), Book_Num: $("#txtnum").val(), Book_Price: $("#txtprice").val(),Book_ID:id},
                success: function () {
                    alert("提交成功");
                    location.href = "/BookAction/Index";
                }
            })
        }
    </script>
</body>
</html>

转载于:https://www.cnblogs.com/jpp666/p/7883088.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值