Vue在MVC中的进行前后端的交互
Preface:
由于最近在研究前端相关的技术,作为前端非常优秀的框架Vue,个人在学习的过程中遇到一些问题,网上相关资料有限,所以在这这里总结一下个人使用Vue的一点经验,以便后来者借鉴!
官方文档:Vue.js
使用Vue在ASP.NET MVC中进行前后端交互
在阅读下面的文章之前你需要先了解一下Vue官方推荐的前后端交互的插件:
1.resource(官方在2.0版本之后取消了对此插件的维护)
2.axios
注:这里使用的都是异步的插件,因为这样才会在你的项目中具有使用意义,当然你也可以用其它的js库,如jQuery、Fetch等等...
Instance:
Controller
using Demo.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; namespace Demo.Controllers
{
//[RoutePrefix("api/Goods")]
public class GoodsController : Controller
{
List<GoodsEntity> goosdList = new List<GoodsEntity>
{
new GoodsEntity(){ ID=,Name="水",Type=,Price=},
new GoodsEntity(){ ID=,Name="牛奶",Type=,Price=},
new GoodsEntity(){ ID=,Name="面包",Type=,Price=}
}; // GET: Goods
public ActionResult Index()
{
return View();
} public ActionResult Check()
{
return View();
} [HttpGet]
public JsonResult GetGoodsType()
{
List<int> goodsType = new List<int>();
foreach (var item in goosdList)
{
if (!goodsType.Contains(item.Type))
{
goodsType.Add(item.Type);
}
}
return Json(goodsType, JsonRequestBehavior.AllowGet);
} [HttpGet]
public JsonResult GetAllGoods()
{
return Json(goosdList, JsonRequestBehavior.AllowGet);
} [HttpPost]
public JsonResult GetGoods(int id)
{
var entity = goosdList.Where(g => g.ID == id).FirstOrDefault();
if (entity != null)
{
return Json(new ReturnJsonInfo(, "success!", entity));
}
return Json(new ReturnJsonInfo(, "error!", null));
} [HttpPost]
public JsonResult UpdateGoods(GoodsEntity entity)
{
if (entity!=null)
{
var goodsEntiy = goosdList.FirstOrDefault(g => g.ID == entity.ID);
if (goodsEntiy!=null)
{
goodsEntiy = entity;
return Json(new ReturnJsonInfo(, "success!", goosdList));
}
goosdList.Add(entity);
return Json(new ReturnJsonInfo(, "success!", goosdList));
}
return Json(new ReturnJsonInfo(, "error!",null));
} [HttpPost]
public JsonResult DelectGoods(int id)
{
var entity = goosdList.Where(g => g.ID == id).FirstOrDefault();
if (entity != null)
{
goosdList.Remove(entity);
return Json(new ReturnJsonInfo(, "success!", goosdList));
}
return Json(new ReturnJsonInfo(, "error!",null));
} }
}
在上面的控制器中加载了一些示例数据,并且都是以json的格式返回前端,这样前端就可以直接使用这些数据。
注:控制器返回至前端的json中,上面使用 “ReturnJsonInfo” 对象序列化进行返回, “ReturnJsonInfo” 代码如下。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace Demo.Models
{
public class ReturnJsonInfo
{
public int Code { get; set; }
public string Message { get; set; }
public object Entity { get; set; }
public ReturnJsonInfo(int code, string message,object obj)
{
this.Code = code;
this.Message = message;
this.Entity = obj;
}
}
}
View
1.前端采用resource插件
 @{
     ViewBag.Title = "Goods IndexPage";
 }
                  <script type="text/javascript" src="~/Resources/Scripts/vue.js"></script>
                  <script type="text/javascript" src="~/Resources/Scripts/vue-resource.js"></script>
 <h2>Index</h2>
                <div id="demo">
                       <table>
                           <tr>
                               <td><label>编号:</label></td>
                               <td><input type="text" v-model="newGoods.id" /></td>
                               <td><label>名称:</label></td>
                               <td><input type="text" v-model="newGoods.name" /></td>
                               <td><label>类型:</label></td>
                               <td><input type="text" v-model="newGoods.type" /></td>
                               <td><label>售价:</label></td>
                               <td><input type="text" v-model="newGoods.price" /></td>
                               <td><input type="submit" value="查询" v-on:click="GetGoods(newGoods.id)" /></td>
                           </tr>
                       </table>
                               <table v-show="goodsList.length">
                                   <tr>
                                       <td>编号</td>
                                       <td>名称</td>
                                       <td>类型</td>
                                       <td>售价</td>
                                   </tr>
                                   <tr v-for="item in goodsList">
                                       <td>{{item.ID}}</td>
                                       <td>{{item.Name}}</td>
                                       <td>{{item.Type}}</td>
                                       <td>{{item.Price}}</td>
                                   </tr>
                               </table>
                </div>
 <script type="text/javascript">
     var view = new Vue(
         {
             el: "#demo",
             data: {
                 goodsList: [],
                 newGoods: {id:'',name:'',type:'',price:''}
             },
             created: function () {
                 this.InIt();
             },
             methods: {
                 InIt: function () {
                     //初始化
                     this.GetAllGoods();
                 },
                 GetAllGoods: function () {
                     var _self = this;
                     _self.$http.get("../Goods/GetAllGoods").then(
                         // Lambda写法
                         (response) => {
                             //successCallback
                             for (var i = 0; i < response.data.length; i++) {
                                 _self.goodsList.push(response.data[i]);
                             }
                         } ,
                         (response) => {
                                    //errorCallback
                         }
                     );
                 },
                 GetGoods: function (_id) {
                     var _self = this;
                     _self.goodsList = [];
                     if (_id.length > 0) {
                         _self.$http.post("../Goods/GetGoods", { id: _id }).then(
                             // 传统写法
                             function (response) {
                                 //successCallback
                                 if (response.data.Code == 500) {
                                     _self.goodsList.push(response.data.Entity);
                                 }
                                 else {
                                     alert(response.data.Message);
                                 }
                             },
                             function (response) {
                                 //errorCallback
                             }
                         )
                             .catch(function (response) {
                                 console.log(response);
                             });
                     }
                     else {
                         _self.GetAllGoods();
                     }
             }
             }
         }
     );
 </script>
2.前端采用axios插件
 @{
     Layout = null;
 }
 <!DOCTYPE html>
 <html>
 <head>
     <meta name="viewport" content="width=device-width" />
     <title>Check</title>
     <script type="text/javascript" src="~/Resources/Scripts/vue.js"></script>
     <script type="text/javascript" src="~/Resources/Scripts/axios.min.js"></script>
 </head>
 <body>
     <div id="demo">
         <div>
             <table>
                 <tr>
                     <td><label>编号:</label></td>
                     <td><input type="text" v-model="newGoods.id" /></td>
                     <td><label>名称:</label></td>
                     <td><input type="text" v-model="newGoods.name" /></td>
                     <td><label>类型:</label></td>
                     <td>
                         <select v-model="newGoods.type">
                             <option value="">---ALL---</option>
                             <option v-for="type in goodsType" v-bind:value="type">{{type}}</option>
                         </select>
                     </td>
                     <td><label>售价:</label></td>
                     <td><input type="text" v-model="newGoods.price" /></td>
                     <td>
                         <input type="submit" value="查询" v-on:click="GetGoods(newGoods.id)" />
                         <input type="submit" value="更新" v-on:click="UpdateGoods(newGoods.id,newGoods.name,newGoods.type,newGoods.price)" />
                         <input type="submit" value="删除" v-on:click="DelectGoods(newGoods.id)" />
                     </td>
                 </tr>
             </table>
         </div>
         <div>
             <table v-show="goodsList.length">
                 <tr>
                     <td>行号</td>
                     <td>编号</td>
                     <td>名称</td>
                     <td>类型</td>
                     <td>售价</td>
                 </tr>
                 <tr v-for="(item,index) in goodsList">
                     <td>{{index+1}}</td>
                     <td>{{item.ID}}</td>
                     <td>{{item.Name}}</td>
                     <td>{{item.Type}}</td>
                     <td>{{item.Price}}</td>
                 </tr>
             </table>
         </div>
     </div>
     <script type="text/javascript">
         var vm = new Vue({
             el: "#demo",
             data: {
                 goodsType:[],
                 goodsList: [],
                 newGoods: { id: '', name: '', type: '', price: '' }
             },
             mounted() {
                 this.GetGoodsType();
                 this.GetAllGoods();
             },
             methods:
             {
                 GetGoodsType: function () {
                     axios.get("../Goods/GetGoodsType").then(
                         (response) => {
                             this.goodsType = [];
                             for (var i = 0; i < response.data.length; i++) {
                                 this.goodsType.push(response.data[i]);
                             }
                         },
                         (response) => {
                             alert(response.status);
                         }
                     )
                         .catch(function (response) {
                             console.log(response);
                         });
                 } ,
                 GetAllGoods: function () {
                     axios.get('../Goods/GetAllGoods').then(
                         function (response) {
                             vm.goodsList = [];
                             for (var i = 0; i < response.data.length; i++) {
                                 vm.goodsList.push(response.data[i]);
                             }
                             //vm.goodsList.splice(response.data.length);
                         },
                         function (response) {
                             alert(response.status);
                         }
                     )
                         .catch(
                         function (error) {
                             alert(error);
                         }
                         )
                 },
                 GetGoods: function (_id) {
                     if (_id.length > 0) {
                         axios.post("../Goods/GetGoods", { id: _id }).then(
                             (response) => {
                                 this.goodsList = [];
                                 if (response.data.Code == 500) {
                                     this.goodsList.push(response.data.Entity);
                                 }
                                 else {
                                     alert(response.data.Message);
                                 }
                             },
                             (response) => {
                                 alert(response.status);
                             }
                         )
                             .catch(function (response) {
                                 console.log(response);
                             });
                     }
                     else {
                         this.GetAllGoods();
                     }
                 },
                 UpdateGoods: function (_id,_name,_type,_price) {
                     axios.post("../Goods/UpdateGoods", { entity: { ID: _id, Name: _name, Type: _type, Price: _price } }).then(
                         (response) => {
                             this.goodsList = [];
                             if (response.data.Code == 500) {
                                 for (var i = 0; i < response.data.Entity.length; i++) {
                                     this.goodsList.push(response.data.Entity[i]);
                                 }
                             }
                             else {
                                 alert(response.data.Message);
                             }
                         },
                         (response) => {
                             alert(response.status);
                         }
                     )
                         .catch(function (response) {
                             console.log(response);
                         });
                 },
                 DelectGoods: function (_id) {
                     axios.post("../Goods/DelectGoods", { id: _id }).then(
                         (response) => {
                             this.goodsList = [];
                             if (response.data.Code == 500) {
                                 for (var i = 0; i < response.data.Entity.length; i++) {
                                     this.goodsList.push(response.data.Entity[i]);
                                 }
                             }
                             else {
                                 alert(response.data.Message);
                             }
                         },
                         (response) => {
                             alert(response.status);
                         }
                     )
                         .catch(function (response) {
                             console.log(response);
                         });
                 }
             },
         });
     </script>
 </body>
 </html>
在上面的视图中,前端都是用数组进行填充的,值得注意的是vue在数组监听这一块做得并不是特别友好。但也提供了一些非常友好的api。
如果你也采用上述方式更新view,请参阅vue官方提供的关于操作数组方法
Perorations:
在上面的Demo中,采用的是ASP.NET MVC模板。在写View部分的时候感觉确实比较方便,不需要再去写获取元素的代码,只需要把数据绑定至元素上,关注数据的变动就可以了。
当然你也可以选择Razor语法,只不过那样看起来并不是很友善。
以上是个人在写这个Demo之后的一些总结。如有描述不当,请@作者修改,谢谢!
Vue在MVC中的进行前后端的交互的更多相关文章
- Vue在ASP.NET MVC中的进行前后端的交互
		Vue在ASP.NET MVC中的进行前后端的交互 Preface: 由于最近在研究前端相关的技术,作为前端非常优秀的框架Vue,个人在学习的过程中遇到一些问题,网上相关资料有限,所以在这这里总结一下 ... 
- vue-resource的使用,前后端数据交互
		vue-resource的使用,前后端数据交互 1:导入vue与vue-resource的js js下载: https://pan.baidu.com/s/1fs5QaNwcl2AMEyp_kUg ... 
- 对GraphQL-BFF:微服务背景下的前后端数据交互方案的研究-------引用
		随着多终端.多平台.多业务形态.多技术选型等各方面的发展,前后端的数据交互,日益复杂. 同一份数据,可能以多种不同的形态和结构,在多种场景下被消费. 在理想情况下,这些复杂性可以全部由后端承担.前端只 ... 
- SpringMVC前后端分离交互传参详细教程
		温故而知新,本文为一时兴起写出,如有错误还请指正 本文后台基于SpringBoot2.5.6编写,前端基于Vue2 + axios和微信小程序JS版分别编写进行联调测试,用于理解前后端分离式开发的交互 ... 
- 两种方法实现asp.net方案的前后端数据交互(aspx文件、html+ashx+ajax)
		一个HTML页面只能显示HTML代码信息,不能与数据库进行数据的交互.asp.net方案提供了网页与数据库交互的方法,这里举出两种:①aspx文件 ②ashx文件+ajax技术 一.创建数据库 这里以 ... 
- 前后端API交互数据加密——AES与RSA混合加密完整实例
		前言 前段时间看到一篇文章讲如何保证API调用时数据的安全性(传送门:https://blog.csdn.net/ityouknow/article/details/80603617),文中讲到利用R ... 
- web前后端数据交互
		前后端数据交互是每一名web程序员必须熟悉的过程,前后端的数据交互重点在于前端是如何获取后端返回的数据,毕竟后端一般情况下只需要将数据封装到一个jsonMap,然后return就完了.下面通过一个li ... 
- 前后端数据交互利器--Protobuf
		Protobuf 介绍 Protocol Buffers(又名 protobuf)是 Google 的语言中立.平台中立.可扩展的结构化数据序列化机制. https://github.com/prot ... 
- 前后端数据交互(八)——请求方法 GET 和 POST 区别
		WEB 开发同学一看 get 和 post 请求方法的区别,第一感觉都是 So easy! 学习ajax.fetch.axios时,发送网络请求携带参数时,都需要分别处理get和post的参数.所以我 ... 
随机推荐
- Android高效率编码-第三方SDK详解系列(二)——Bmob后端云开发,实现登录注册,更改资料,修改密码,邮箱验证,上传,下载,推送消息,缩略图加载等功能
			Android高效率编码-第三方SDK详解系列(二)--Bmob后端云开发,实现登录注册,更改资料,修改密码,邮箱验证,上传,下载,推送消息,缩略图加载等功能 我的本意是第二篇写Mob的shareSD ... 
- 单片机PWM调制技术
			我们可以看看下图,下图就是一个典型的PWM的波形图. T是一个周期,T1就是高电平所占用的时间,T2就是低电平所占用的时间. 如上图所示T1为脉冲宽度(就是导通时间),周期为T,则输出电压的平均值为U ... 
- 第15章-输入/输出 --- 理解Java的IO流
			(一)理解Java的IO流 JAVA的IO流是实现输入/输出的基础,它可以方便地实现数据的输入/输出操作,在Java中把不同的输入/输出(键盘.文件.网络连接等)抽象表述为"流"( ... 
- DIV与SPAN之间有什么区别
			DIV与SPAN之间有什么区别 DIV 和 SPAN 元素最大的特点是默认都没有对元素内的对象进行任何格式化渲染.主要用于应用样式表(共同点). 两者最明显的区别在于DIV是块元素,而SPAN是行内元 ... 
- Python字符串全解
			1.字符串大小写转换 def strChange(): str = "niuXinLong@163.com" print("原字符串:" + str) prin ... 
- JMeter——简单的接口测试实例(一)
			场景:使用JMeter来实现接口测试 基本流程:添加线程组->添加http信息头管理器->添加http请求->添加断言->添加监听器->执行,查看结果 案例分析:下面以办 ... 
- Angular TypeScript开发环境集成jQuery扩展插件
			集成步骤: 1.安装jquery极其扩展插件库ts定义文件 npm install jquery --save npm install --save-dev @types/jquery npm ins ... 
- Kotlin : Retrofit + RxAndroid + Realm
			https://jqs7.com/kotlin-retrofit-rxandroid-realm/ 原作者:Ahmed Rizwan 原文链接:Kotlin : Retrofit + RxAndroi ... 
- Android面试题摘录
			本文中面试题全部选自<精通Android>(英文名“Pro android 4”)一书的章后面试题,不过这套面试题与书中内容结合比较紧密,所以选择使用时请谨慎. ####C2:Androi ... 
- C语言代码
			//计算1/1+1/ (1+2) +1/ (1+2+3) +…+1/(1+2+…n)的值,要求小数点后保留6位,n从键盘输入 #include<stdio.h> main(){ ; ; i ... 
