.NET MVC第十章 vue axios解析web api接口

本文涉及的产品
云解析 DNS,旗舰版 1个月
全局流量管理 GTM,标准版 1个月
公共DNS(含HTTPDNS解析),每月1000万次HTTP解析
简介: .NET MVC第十章 vue axios解析web api接口

数据库

我用的是之前的数据库,用作测试,数据库的名称是【girl1804】


/*
Navicat SQL Server Data Transfer
Source Server         : mysqlserver
Source Server Version : 120000
Source Host           : .:1433
Source Database       : girl1804
Source Schema         : dbo
Target Server Type    : SQL Server
Target Server Version : 120000
File Encoding         : 65001
Date: 2022-10-05 20:24:26
*/
-- ----------------------------
-- Table structure for [dbo].[girlSix]
-- ----------------------------
DROP TABLE [dbo].[girlSix]
GO
CREATE TABLE [dbo].[girlSix] (
[id] varchar(32) NOT NULL DEFAULT (replace(newid(),'-','')) ,
[createDate] datetime NOT NULL DEFAULT (getdate()) ,
[nickName] varchar(30) NOT NULL ,
[introduce] nvarchar(200) NOT NULL 
)
GO
IF ((SELECT COUNT(*) from fn_listextendedproperty('MS_Description', 
'SCHEMA', N'dbo', 
'TABLE', N'girlSix', 
'COLUMN', N'nickName')) > 0) 
EXEC sp_updateextendedproperty @name = N'MS_Description', @value = N'名字'
, @level0type = 'SCHEMA', @level0name = N'dbo'
, @level1type = 'TABLE', @level1name = N'girlSix'
, @level2type = 'COLUMN', @level2name = N'nickName'
ELSE
EXEC sp_addextendedproperty @name = N'MS_Description', @value = N'名字'
, @level0type = 'SCHEMA', @level0name = N'dbo'
, @level1type = 'TABLE', @level1name = N'girlSix'
, @level2type = 'COLUMN', @level2name = N'nickName'
GO
IF ((SELECT COUNT(*) from fn_listextendedproperty('MS_Description', 
'SCHEMA', N'dbo', 
'TABLE', N'girlSix', 
'COLUMN', N'introduce')) > 0) 
EXEC sp_updateextendedproperty @name = N'MS_Description', @value = N'介绍'
, @level0type = 'SCHEMA', @level0name = N'dbo'
, @level1type = 'TABLE', @level1name = N'girlSix'
, @level2type = 'COLUMN', @level2name = N'introduce'
ELSE
EXEC sp_addextendedproperty @name = N'MS_Description', @value = N'介绍'
, @level0type = 'SCHEMA', @level0name = N'dbo'
, @level1type = 'TABLE', @level1name = N'girlSix'
, @level2type = 'COLUMN', @level2name = N'introduce'
GO
-- ----------------------------
-- Records of girlSix
-- ----------------------------
INSERT INTO [dbo].[girlSix] ([id], [createDate], [nickName], [introduce]) VALUES (N'04e3d962adcb4a5b8fefaf8b46995e85', N'2020-05-27 09:05:52.000', N'董新颖', N'郭老师关门弟子之一。');
GO
INSERT INTO [dbo].[girlSix] ([id], [createDate], [nickName], [introduce]) VALUES (N'568fc305930347d3bec1ddd08c71ad29', N'2020-05-27 09:01:09.000', N'王笑涵', N'北方有佳人,绝世而独立。');
GO
INSERT INTO [dbo].[girlSix] ([id], [createDate], [nickName], [introduce]) VALUES (N'7eaa67475f0c4086a5e76ba1731196d2', N'2022-06-12 11:23:16.000', N'夏天', N'保持每天好心情。');
GO
INSERT INTO [dbo].[girlSix] ([id], [createDate], [nickName], [introduce]) VALUES (N'972ec358089042e0bf24fd9efca47bde', N'2020-05-27 08:59:49.000', N'牛龙珠', N'笑若桃花三月开,清风徐徐醉颜来。');
GO
INSERT INTO [dbo].[girlSix] ([id], [createDate], [nickName], [introduce]) VALUES (N'BDFFC6A36A53408281EB8CA242C0E7A3', N'2020-05-27 08:42:31.000', N'闫春娜', N'珠缨旋转星宿摇,花蔓抖擞龙蛇动。');
GO
INSERT INTO [dbo].[girlSix] ([id], [createDate], [nickName], [introduce]) VALUES (N'd1cdd67717e549caba16503787b55877', N'2021-02-17 15:27:41.357', N'小龙女', N'想过过过儿过过的日子');
GO
INSERT INTO [dbo].[girlSix] ([id], [createDate], [nickName], [introduce]) VALUES (N'efb0ca854dac456b9d8c42d4c4b1bce0', N'2020-05-27 09:03:30.000', N'刘梓佳', N'明眸善睐,辅靥承权,瑰姿艳逸,怡静体闲,端的是好一个花王,富贵的牡丹。');
GO
INSERT INTO [dbo].[girlSix] ([id], [createDate], [nickName], [introduce]) VALUES (N'f839343b980e45caafaa9d2c9797294b', N'2020-05-27 09:04:53.000', N'魏慧娟', N'脉脉眼中波,盈盈花盛处。');
GO
-- ----------------------------
-- Indexes structure for table girlSix
-- ----------------------------
-- ----------------------------
-- Primary Key structure for table [dbo].[girlSix]
-- ----------------------------
ALTER TABLE [dbo].[girlSix] ADD PRIMARY KEY ([id])
GO

EF引入数据

image.png


等待完成后即可。


我们需要使用的是girl1804Entities

image.png



创建API控制器

image.png




接口编码

为了方便操作,我都写成HTTPGET请求了


获取信息


/// <summary>
/// 获取信息接口
/// </summary>
/// <returns></returns>
public object GetInfo()
{
    using (girl1804Entities db = new girl1804Entities())
    {
        return db.girlSix.ToList();
    }
}

添加信息


/// <summary>
/// 添加
/// </summary>
/// <param name="nickName"></param>
/// <param name="introduce"></param>
/// <returns></returns>
[HttpGet]
public bool AddInfo(string nickName, string introduce)
{
    using (girl1804Entities db = new girl1804Entities())
    {
        girlSix g = new girlSix();
        g.id = System.Guid.NewGuid().ToString("N");
        g.createDate = DateTime.Now;
        g.nickName = nickName;
        g.introduce = introduce;
        db.girlSix.Add(g);
        return db.SaveChanges() > 0;
    }
}


删除信息


/// <summary>
/// 删除
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet]
public object DeleteById(string id)
{
    using (girl1804Entities db = new girl1804Entities())
    {
        girlSix g = db.girlSix.Where(o => o.id == id).SingleOrDefault();
        db.girlSix.Remove(g);
        return db.SaveChanges() > 0;
    }
}

单个查询


/// <summary>
/// 单个查询
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet]
public object SelectById(string id)
{
    using (girl1804Entities db = new girl1804Entities())
    {
        return db.girlSix.Where(o => o.id == id).SingleOrDefault();
    }
}

修改方法

/// <summary>
/// 修改方法
/// </summary>
/// <param name="id"></param>
/// <param name="nickName"></param>
/// <param name="introduce"></param>
/// <returns></returns>
[HttpGet]
public bool UpdateById(string id, string nickName, string introduce)
{
    using (girl1804Entities db = new girl1804Entities())
    {
        girlSix girlSix = db.girlSix.Where(o => o.id == id).SingleOrDefault();
        if (girlSix == null)
        {
            return false;
        }
        girlSix.nickName = nickName;
        girlSix.introduce = introduce;
        return db.SaveChanges()>0;
    }
}


获取接口

image.png

接口


http://localhost:1246/api/gril1804/GetInfo
http://localhost:1246/api/gril1804/AddInfo?nickName={nickName}&introduce={introduce}
http://localhost:1246/api/gril1804/DeleteById/{id}
http://localhost:1246/api/gril1804/SelectById/{id}
http://localhost:1246/api/gril1804/UpdateById/{id}?nickName={nickName}&introduce={introduce}

根据接口解析操作即可。


网络js环境

bootstrap-css:【<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">】


JQuery:【<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>】


bootstrap:【<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>】


vue:【<script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>】


axios:【<script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>】


 

<!--用于bootstrap样式-->
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
    <!--用于bootstrap-->
    <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
    <!--用于样式-->
    <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <!--用于基础操作-->
    <script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>
    <!--用于数据解析-->
    <script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>

完整示例:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!--用于bootstrap样式-->
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
    <div id="app">
        <div class="input-group">
            <span class="input-group-addon">昵称搜索:</span>
            <input type="text" v-model="selectKey" placeholder="请输入搜索昵称关键字" class="form-control" />
        </div>
        <table class="table table-bordered table-hover">
            <tr class="info">
                <th>编号</th>
                <th>创建时间</th>
                <th>昵称</th>
                <th>介绍</th>
                <th>操作</th>
            </tr>
            <!--遍历过滤后的集合-->
            <tr v-for="item in newlist">
                <td>{{item.id}}</td>
                <td>{{item.createDate}}</td>
                <td>{{item.nickName}}</td>
                <td>{{item.introduce}}</td>
                <td>
                    <button v-on:click="del(item.id)" class="btn btn-info">删除</button>
                    <button v-on:click="SetInfo(item)" class="btn btn-info">修改</button>
                </td>
            </tr>
        </table>
        <hr/>
        <div class="input-group">
            <span class="input-group-addon">编号:</span>
            <input type="text" v-model="id" disabled class="form-control" />
        </div>
        <div class="input-group">
            <span class="input-group-addon">创建时间:</span>
            <input type="text" v-model="createDate" disabled class="form-control" />
        </div>
        <div class="input-group">
            <span class="input-group-addon">昵称:</span>
            <input type="text" v-model="nickName" class="form-control" />
        </div>
        <div class="input-group">
            <span class="input-group-addon">简介:</span>
            <input type="text" v-model="introduce" class="form-control" />
        </div>
        <button v-on:click="Setting()" class="btn btn-info">完成修改</button>
        <button v-on:click="add()" class="btn btn-info">添加</button>
    </div>
    <!--用于bootstrap-->
    <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
    <!--用于样式-->
    <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <!--用于基础操作-->
    <script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>
    <!--用于数据解析-->
    <script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
    <script>
        var urlBase = "http://localhost:1246/api/gril1804/";
        new Vue({
            el: "#app",
            data: {
                list: [],
                selectKey: "",
                id: "",
                createDate: "",
                nickName: "",
                introduce: ""
            },
            created() { //获取数据
                var _this = this;
                var url = urlBase + "GetInfo";
                axios.get(url).then(function(retult) {
                    console.log(retult.data);
                    _this.list = retult.data;
                })
            },
            computed: { //过滤数据
                newlist: function() {
                    var _this = this;
                    console.log(_this.list);
                    return _this.list.filter(function(o) {
                        return o.nickName.indexOf(_this.selectKey) != -1;
                    });
                }
            },
            methods: { //方法集合
                add: function() {
                    var url = urlBase + "addInfo?nickName=" + this.nickName + "&introduce=" + this.introduce;
                    axios.get(url).then(function(retult) {
                        if (retult.data) {
                            alert("添加成功");
                            location.reload();
                        }
                    })
                },
                del: function(o) {
                    if (confirm("是否删除此行")) {
                        var url = urlBase + "DeleteById?id=" + o;
                        axios.get(url).then(function(retult) {
                            alert("删除成功");
                            location.reload();
                        })
                    }
                },
                SetInfo: function(item) { //修改1
                    this.id = item.id;
                    this.createDate = item.createDate;
                    this.nickName = item.nickName;
                    this.introduce = item.introduce;
                },
                Setting: function() { //修改2
                    var url = urlBase + "UpdateById?id=" + this.id + "&nickName=" + this.nickName + "&introduce=" + this.introduce;
                    axios.get(url).then(function(retult) {
                        if (retult.data) {
                            alert("修改成功");
                            location.reload();
                        }
                    })
                }
            }
        })
    </script>
</body>
</html>


image.png


总结

axios使用方法相对更方便一些,加载数据也只需要在created中处理即可,如果有需要的话就搭建一个脚手架,如果不方便话使用那个都无所谓的,功能是肯定可以实现的,前提是接口一定要跨域啊,如果接口没有跨域是无法进行解析的。

相关实践学习
Serverless极速搭建Hexo博客
本场景介绍如何使用阿里云函数计算服务命令行工具快速搭建一个Hexo博客。
相关文章
|
11天前
|
开发框架 JSON 缓存
震撼发布!Python Web开发框架下的RESTful API设计全攻略,让数据交互更自由!
在数字化浪潮推动下,RESTful API成为Web开发中不可或缺的部分。本文详细介绍了在Python环境下如何设计并实现高效、可扩展的RESTful API,涵盖框架选择、资源定义、HTTP方法应用及响应格式设计等内容,并提供了基于Flask的示例代码。此外,还讨论了版本控制、文档化、安全性和性能优化等最佳实践,帮助开发者实现更流畅的数据交互体验。
32 1
|
29天前
|
监控 网络协议 API
.NET WebSocket 技术深入解析,你学会了吗?
【9月更文挑战第4天】WebSocket 作为一种全双工协议,凭借低延迟和高性能特点,成为实时应用的首选技术。.NET 框架提供了强大的 WebSocket 支持,使实时通信变得简单。本文介绍 WebSocket 的基本概念、.NET 中的使用方法及编程模型,并探讨其在实时聊天、监控、在线游戏和协同编辑等场景的应用,同时分享最佳实践,帮助开发者构建高效实时应用。
80 12
|
29天前
|
开发框架 前端开发 JavaScript
ASP.NET MVC 教程
ASP.NET 是一个使用 HTML、CSS、JavaScript 和服务器脚本创建网页和网站的开发框架。
28 7
|
1月前
|
前端开发 安全 Java
技术进阶:使用Spring MVC构建适应未来的响应式Web应用
【9月更文挑战第2天】随着移动设备的普及,响应式设计至关重要。Spring MVC作为强大的Java Web框架,助力开发者创建适应多屏的应用。本文推荐使用Thymeleaf整合视图,通过简洁的HTML代码提高前端灵活性;采用`@ResponseBody`与`Callable`实现异步处理,优化应用响应速度;运用`@ControllerAdvice`统一异常管理,保持代码整洁;借助Jackson简化JSON处理;利用Spring Security增强安全性;并强调测试的重要性。遵循这些实践,将大幅提升开发效率和应用质量。
54 7
|
1月前
|
前端开发 测试技术 开发者
MVC模式在现代Web开发中有哪些优势和局限性?
MVC模式在现代Web开发中有哪些优势和局限性?
|
27天前
|
存储 开发框架 前端开发
ASP.NET MVC 迅速集成 SignalR
ASP.NET MVC 迅速集成 SignalR
38 0
|
2月前
|
C# Windows 开发者
超越选择焦虑:深入解析WinForms、WPF与UWP——谁才是打造顶级.NET桌面应用的终极利器?从开发效率到视觉享受,全面解读三大框架优劣,助你精准匹配项目需求,构建完美桌面应用生态系统
【8月更文挑战第31天】.NET框架为开发者提供了多种桌面应用开发选项,包括WinForms、WPF和UWP。WinForms简单易用,适合快速开发基本应用;WPF提供强大的UI设计工具和丰富的视觉体验,支持XAML,易于实现复杂布局;UWP专为Windows 10设计,支持多设备,充分利用现代硬件特性。本文通过示例代码详细介绍这三种框架的特点,帮助读者根据项目需求做出明智选择。以下是各框架的简单示例代码,便于理解其基本用法。
73 0
|
2月前
|
开发者 前端开发 Java
架构模式的诗与远方:如何在MVC的田野上,用Struts 2编织Web开发的新篇章
【8月更文挑战第31天】架构模式是软件开发的核心概念,MVC(Model-View-Controller)通过清晰的分层和职责分离,成为广泛采用的模式。随着业务需求的复杂化,Struts 2框架应运而生,继承MVC优点并引入更多功能。本文探讨从MVC到Struts 2的演进,强调架构模式的重要性。MVC将应用程序分为模型、视图和控制器三部分,提高模块化和可维护性。
36 0
|
2月前
|
Java 开发者 前端开发
Struts 2、Spring MVC、Play Framework 上演巅峰之战,Web 开发的未来何去何从?
【8月更文挑战第31天】在Web应用开发中,Struts 2框架因强大功能和灵活配置备受青睐,但开发者常遇配置错误、类型转换失败、标签属性设置不当及异常处理等问题。本文通过实例解析常见难题与解决方案,如配置文件中遗漏`result`元素致页面跳转失败、日期格式不匹配需自定义转换器、`&lt;s:checkbox&gt;`标签缺少`label`属性致显示不全及Action中未捕获异常影响用户体验等,助您有效应对挑战。
67 0
|
2月前
|
Java 前端开发 Apache
Apache Wicket与Spring MVC等Java Web框架大PK,究竟谁才是你的最佳拍档?点击揭秘!
【8月更文挑战第31天】在Java Web开发领域,众多框架各具特色。Apache Wicket以组件化开发和易用性脱颖而出,提高了代码的可维护性和可读性。相比之下,Spring MVC拥有强大的生态系统,但学习曲线较陡;JSF与Java EE紧密集成,但在性能和灵活性上略逊一筹;Struts2虽成熟,但在RESTful API支持上不足。选择框架时还需考虑社区支持和文档完善程度。希望本文能帮助开发者找到最适合自己的框架。
31 0

推荐镜像

更多
下一篇
无影云桌面