Vue在ASP.NET 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在ASP.NET MVC中的进行前后端的交互的更多相关文章

  1. Vue在MVC中的进行前后端的交互

    Vue在MVC中的进行前后端的交互 Preface: 由于最近在研究前端相关的技术,作为前端非常优秀的框架Vue,个人在学习的过程中遇到一些问题,网上相关资料有限,所以在这这里总结一下个人使用Vue的 ...

  2. 2.ASP.NET MVC 中使用Crystal Report水晶报表

    上一篇,介绍了怎么导出Excel文件,这篇文章介绍在ASP.NET MVC中使用水晶报表. 项目源码下载:https://github.com/caofangsheng93/CrystalReport ...

  3. 关于 ASP.NET MVC 中的视图生成

    在 ASP.NET MVC 中,我们将前端的呈现划分为三个独立的部分来实现,Controller 用来控制用户的操作,View 用来控制呈现的内容,Model 用来表示处理的数据. 从控制器到视图 通 ...

  4. 在Asp.Net MVC 中配置 Serilog

    Serilog 是一种非常简便记录log 的处理方式,使用Serilog可以生成本地的text文件, 也可以通过 Seq 来在Web界面中查看具体的log内容. 接下来就简单的介绍一下在Asp.Net ...

  5. 如何在 ASP.NET MVC 中集成 AngularJS(3)

    今天来为大家介绍如何在 ASP.NET MVC 中集成 AngularJS 的最后一部分内容. 调试路由表 - HTML 缓存清除 就在我以为示例应用程序完成之后,我意识到,我必须提供两个版本的路由表 ...

  6. 如何在 ASP.NET MVC 中集成 AngularJS(2)

    在如何在 ASP.NET MVC 中集成 AngularJS(1)中,我们介绍了 ASP.NET MVC 捆绑和压缩.应用程序版本自动刷新和工程构建等内容. 下面介绍如何在 ASP.NET MVC 中 ...

  7. 《Entity Framework 6 Recipes》中文翻译系列 (20) -----第四章 ASP.NET MVC中使用实体框架之在MVC中构建一个CRUD示例

    翻译的初衷以及为什么选择<Entity Framework 6 Recipes>来学习,请看本系列开篇 第四章  ASP.NET MVC中使用实体框架 ASP.NET是一个免费的Web框架 ...

  8. asp.net mvc 中 一种简单的 URL 重写

    asp.net mvc 中 一种简单的 URL 重写 Intro 在项目中想增加一个公告的功能,但是又不想直接用默认带的那种路由,感觉好low逼,想弄成那种伪静态化的路由 (别问我为什么不直接静态化, ...

  9. 在 ASP.NET MVC 中充分利用 WebGrid (microsoft 官方示例)

    在 ASP.NET MVC 中充分利用 WebGrid https://msdn.microsoft.com/zh-cn/magazine/hh288075.aspx Stuart Leeks 下载代 ...

随机推荐

  1. Mysql初学入门

    最近研究了一下Mysql的初学应用,在此进行整理记录. 1.Windows系统下的安装 我用的是win10系统,在http://dev.mysql.com/downloads/mysql/ 下载相应版 ...

  2. 源码安装python +NGINX 的坎坷路 +uwsgi安装 部署django 的CRM项目

    一.Nginx安装(基于ubuntu17.10 版本) 首先我们是基于源码安装,主要有如下步骤 1.安装依赖包 1.安装gcc g++的依赖库 sudo apt-get install build-e ...

  3. [LeetCode] Peak Index in a Mountain Array 山形数组的顶峰坐标

    Let's call an array A a mountain if the following properties hold: A.length >= 3 There exists som ...

  4. phpstorm 断点调试 傻瓜教程

    前言: 简单介绍下为什么要用断点调试,很多人说我在代码调试的部位用var_dump 或者 exit 或者print_r来进行断点,但是当项目足够大的时候这样的做法就比较费时费力,因为你断点后需要删除原 ...

  5. [转] Quality Of Service In OpenStack

    http://tropicaldevel.wordpress.com/2013/07/15/quality-of-service-in-openstack/ In this post I will b ...

  6. 在React Native中,使用fetch网络请求 实现get 和 post

    //在React Native中,使用fetch实现网络请求 /* fetch 是一个封装程度更高的网络API, 使用了Promise * Promise 是异步编程的一种解决方案 * Promise ...

  7. 美团App用户界面分析

    关于美团 美团网成立于2010年,合并前是中国销售额最大的独立团购 App.美团网2014年全年交易额突破460亿元,较去年增长180%以上,市场份额占比超60%,用户数超2亿~ 美团 App 用户界 ...

  8. #Java学习之路——面试题

    (一)[基础知识梳理——JAVAse部分]Java中的变量和常量        在程序中存在大量的数据来代表程序的状态,其中有些数据在程序的运行过程中值会发生改变,有些数据在程序运行过程中值不能发生改 ...

  9. input使用小技巧

    ①:如何修改placeholder样式? input::-webkit-input-placeholder { color: #ccc; font-size: 15px; } 注:其它浏览器适配方案 ...

  10. [Swift]LeetCode25. k个一组翻转链表 | Reverse Nodes in k-Group

    Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. k  ...