zoukankan      html  css  js  c++  java
  • 第8章 ASP.NET(MVC Web API)

    一、      ASP.NET Web API 简介

    二、      创建一个 Web API 程序

    1、         环境准备

    2、         创建Web API程序

    3、         在Web API中添加代码

    4、         浏览器的访问

    5、         JavaScript访问web api

    三、      理解 API的路由

    四、      Web API 工作方式

    结合上一章内容本章内容将运用MVC API实现分类增删改查

     一、在“LinqBLL”添加一个类名为“CategoryBll.cs”编辑“增删改查”方法

    1、如图所示(加载数据):

    2、如图所示(删除)

    3、如图所示(添加)

    4、如图所示(修改)

    代码示例:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    using LinqService;
    using LinqBLL;
    namespace LinqBLL
    {
       public class CategoryBll
        {
           //显示
           public List<Categories> GetCategories()
           {
               using (SportsStoreEntities st = new SportsStoreEntities())
               {
                   var s = from a in st.Categories
                           select a;
                   return s.ToList<Categories>();
               }
           }
           //删除
           public bool Delete(int id)
           {
               bool b = true;
               try
               {
                   using (SportsStoreEntities st = new SportsStoreEntities())
                   {
                       Categories model = st.Categories.SingleOrDefault(a => a.Id == id);
                       st.Categories.Remove(model);
                       st.SaveChanges();
                   }
               }
               catch (Exception ex)
               {
                   b = false;
                   throw new Exception(ex.ToString());
               }
               return b;
           }
           //添加分类
           public bool Create(Categories model)
           {
               bool b = true;
               try
               {
                   using (SportsStoreEntities st = new SportsStoreEntities())
                   {
                       st.Categories.Add(model);
                       st.SaveChanges();
                   }
               }
               catch (Exception ex)
               {
                   b = false;
                   throw new Exception(ex.ToString());
               }
               return b;
           }
           //修改分类
           public bool Update(Categories model)
           {
               bool b = true;
               try
               {
                   using (SportsStoreEntities st = new SportsStoreEntities())
                   {
                       Categories info = st.Categories.FirstOrDefault(a => a.Id == model.Id);
                       info.Name = model.Name;
                       st.SaveChanges();
                   }
               }
               catch (Exception ex)
               {
    
                   b = false;
                   throw new Exception(ex.ToString());
               }
               return b;
           }
        }
    }
    View Code

     二、编辑完成后,到“MvcProduct/Controllers”添加一个“Web API控制器类”并调用“增删改查”方法

    1、如图所示:

    2、如图所示(获取分类方法调用)

    3、如图所示(添,修,删,调用)

    代码示例:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Web.Http;
    
    using LinqService;
    using LinqBLL;
    namespace MvcProduct.Controllers
    {
        public class CategoryController : ApiController
        {
            CategoryBll bll = new CategoryBll();
            // GET api/<controller>
            //获取分类
            public IEnumerable<Categories> Get()
            {
                List<Categories> lst = bll.GetCategories();
                return lst;
            }
    
            // GET api/<controller>/5
            public string Get(int id)
            {
                return "value";
            }
    
            // 添加
            public bool Post(Categories model)
            {
                return bll.Create(model);
            }
    
            // 修改
            public bool Put(Categories model)
            {
                return bll.Update(model);
            }
    
            // 删除
            public bool Delete(int id)
            {
                return bll.Delete(id);
            }
        }
    }
    View Code

    三、完成后,到“Areas/Areas/Controllers”添加一个控制器名为“CategoryController.cs”,

          然后在“CategoryController.cs”里面“Index方法”添加一个视图并运用“ajax”编辑“增删改查”方法

     1、如图所示(添加”控制器“与”视图“)

    2、如图所示(数据加载)

    3、如图所示(添加与修改)

    4、如图所示(删除与编辑模板)

    代码示例:

    @{
        ViewBag.Title = "Index";
    }
    <script src="../../../../Scripts/jquery-1.7.1.js"></script>
    <script type="text/javascript">
        $(function () {
            LoadData();
            $("#btnAdd").click(function () {
                Add();
            });
        });
        //数据加载
        function LoadData() {
            $.ajax({
                url: "/api/Category/",
                type: "GET",
                async: false,
                dataType: "json",
                success: function (data) {
                    $("#tab tr:gt(0)").remove();
                    $.each(data, function (i, cate) {
                        var tr = $("#tab tr:eq(0)").clone();
                        var tds = tr.find("td");
                        tds.eq(0).text(i + 1);
                        tds.eq(1).html("<input tyoe='text' value='" + cate.Name + "'/>");
                        tds.eq(2).html(" <input type='button' value='改' onclick='Update(this," + cate.Id + ")'/>");
                        tds.eq(3).html(" <input type='button' value='删' onclick='deletes(" + cate.Id + ")' />");
                        $("#tab").append(tr);
                    });
                }
            });
        }
        //添加
        function Add() {
            $.ajax({
                url: "/api/Category/",
                type: "POST",
                data: { "Name": $("#txtName").val() },
                success: function (data) {
                    if (data)
                        LoadData();
                    else
                        alert("添加失败");
                }
            })
        }
        //修改
        function Update(value, id) {
            var txtname = $(value).parent().prev().children().val();
            $.ajax({
                url: "/api/Category/",
                type: "Put",
                data: { "Id": id, "Name": txtname },
                success: function (data) {
                    if (data)
                        alert("修改成功!");
                    else
                        alert("修改失败!");
                }
            })
        }
        //删除
        function deletes(id) {
            if (confirm("确认要删除吗?")) {
                $.ajax({
                    url: "/api/Category/" + id,
                    type: "DELETE",
                    success: function (data) {
                        if (data)
                            LoadData();
                        else
                            alert("删除失败!");
                    }
                })
            }
        }
    </script>
    <h2>分类管理</h2>
    <fieldset>
        <legend>分类管理</legend>
        <table>
            <tr>
                <td>分类名称:<input type="text" id="txtName" />&nbsp;
                    <input type="button" id="btnAdd" value="添加" />
                </td>
            </tr>
        </table>
        <table id="tab">
            <tr style="height:25px">
                <td>序号</td>
                <td>名称</td>
                 <td>改</td>
                 <td>删</td>
            </tr>
        </table>
    </fieldset>
    View Code

    四、到“Areas/Areas/Shared/_Layout.cshtml”添加一行菜单

    如图所示:

    代码示例:

    <!DOCTYPE html>
    <html>
    <head>
        <title>@ViewBag.Title</title>
          <link href="@Url.Content("~/Content/Product.css")" rel="stylesheet" type="text/css" />
        <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
        <script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
    </head>
    <body>
        <div class="page">
            <div id="header">
                <div id="title">
                    <h1>在线后台管理体育产品</h1>
                </div>
                <div id="logindisplay">
                    @Html.Partial("_LogOnPartial")
                </div>
                <div id="menucontainer">
                    <ul id="menu">
                        <li>@Html.ActionLink("首页", "Index", "Home")</li>
                        <li>@Html.ActionLink("分类管理", "Index", "Category", new  {Area="Areas" },null)</li>
                         <li>@Html.ActionLink("体育管理", "List", "Store", new {Area="Areas" },null)</li>
                        <li>@Html.ActionLink("退出", "LogOff", "Account", new  {Area="" },null)</li>
                    </ul>
                </div>
            </div>
    
            <div id="main">
               @* <div id="categories">
                    @{Html.RenderAction("Menu", "Nav");}
                </div>*@
               <div id="content">
                    @RenderBody()
               </div>
            </div>
        </div>
    </body>
    </html>
    View Code

    注意:因为开发工具版本较低,必须把“路由”改成全局,否则数据显示不出来,在”MvcProduct“项目添加一个文件名为“App_Start”,

             然后在“App_Start”文件添加一个类名为“WebApiConfig.cs”编辑方法,最后到“Global.asax”路由调用

    1、如图所示:(文件与类添加,方法)

    代码示例:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Http;
    
    namespace StroePrc
    {
        public static class WebApiConfig
        {
            public static void Register(HttpConfiguration config)
            {
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
            }
        }
    }
    View Code

    2、如图所示:(调用)

    3、如图所示:(调用)

    运行效果:

     

  • 相关阅读:
    【Django】Django REST Framework简单教程
    【SpringBoot | Druid】SpringBoot整合Druid
    【SpringBoot | Swagger】SpringBoot整合Swagger
    【Vue | ElementUI】Vue离开当前页面时弹出确认框实现
    【SpringBoot | Redis】SpringBoot整合Redis
    【评测机】评测时报错cc1plus: fatal error: /xx/xx/main.cpp: Permission denied compilation terminated.的解决方法
    Hello world!
    【续】将HUSTOJ备份数据并迁移至Ubuntu16.04
    将HUSTOJ备份数据并迁移至Ubuntu16.04
    【BZOJ2118】墨墨的等式【循环节做法】
  • 原文地址:https://www.cnblogs.com/xuyangyang/p/6437485.html
Copyright © 2011-2022 走看看