接觸了一天vue.js,簡單瀏覽了一本關於vue的電子書,就開始動手使用ASP.NET MVC和Vue.js開發一個聯系人管理的小程序。
先看一下這個聯系人管理的小程序的界面,也就是我們大概要實現什么樣的功能。

上面截圖可以看出,這是一個很簡單的表格管理功能。我們先分析一下,上述有哪些功能需要實現:
1、默認先加載出所有的聯系人信息,有信息的行后面的操作那一欄,顯示“修改”、“刪除”,沒有信息的行后面的操作那一欄,顯示“添加”(默認只添加一行需要添加的信息)。
2、點擊“添加”按鈕對應的空白文本框中的內容,即可完成添加聯系人的操作。添加操作完成后,自動添加一行空白行,以便再次添加。
3、編輯任意文本框中的內容,點擊對應行后面的“修改”按鈕,即可完成修改操作。
4、點擊“刪除”按鈕,即可刪除對應行的聯系人記錄
大家可以先思考一下,如果就單獨使用ASP.NET MVC,不使用任何JS或jQuery插件,怎么完成。
下面就開始要正式實現上面的功能,首先我們要准備好后端的內容,就是Model、Controller、Repository這些內容。
Model很簡單,就一個聯系人的類:
public class Contact { public string Id { get; set; } public string Name { get; set; } public string PhoneNo { get; set; } public string EmailAddress { get; set; } }
然后新建一個ContactRepository類,用來提供數據的CRUD操作(這里只是簡單的將數據封裝到static變量中):
public class ContactRepository { private static List<Contact> contacts; static ContactRepository() { contacts = new List<Contact>() { new Contact(){ Id=Guid.NewGuid().ToString(), Name="張三", PhoneNo="123", EmailAddress="zhangsan@gmail.com" }, new Contact(){ Id=Guid.NewGuid().ToString(), Name="李四", PhoneNo="456", EmailAddress="lisi@gmail.com" }, }; } public IEnumerable<Contact> Get() { return contacts; } public Contact Get(string id) { return contacts.FirstOrDefault(t => t.Id == id); } public void Put(Contact contact) { contact.Id = Guid.NewGuid().ToString(); contacts.Add(contact); } public void Post(Contact contact) { Delete(contact.Id); contacts.Add(contact); } public void Delete(string id) { Contact contact = contacts.FirstOrDefault(t => t.Id == id); contacts.Remove(contact); } }
接下來就是ContactController控制器:
public class ContactController : Controller { private static ContactRepository contactRepository = new ContactRepository(); public ActionResult Index() { return View(); } [HttpGet] public JsonResult Get() { return Json(contactRepository.Get(), JsonRequestBehavior.AllowGet); } [HttpPost] public JsonResult Add(Contact contact) { contactRepository.Put(contact); return Json(contactRepository.Get()); } [HttpPost] public JsonResult Update(Contact contact) { contactRepository.Post(contact); return Json(contactRepository.Get()); } [HttpPost] public JsonResult Delete(string id) { var contact = contactRepository.Get(id); contactRepository.Delete(id); return Json(contactRepository.Get()); } }
控制器中的代碼也非常簡單,就是簡單的提供了CRUD對應的Action方法。
上述的操作,是ASP.NET MVC中的常規操作,也可以說是套路。完成了后端(ASP.NET MVC)開發工作,下面就是前端(Vue)開發工作了。
要在項目中使用Vue,首先要導入Vue的js文件,可以直接將Vue.js拷貝到Scripts目錄中。此外由於我們需要在cshtml中發起ajax請求,調用controller中的各種action方法,因此我們也需要引用vue的ajax插件-axios。它們都可以通過NuGet在線安裝。引用vue、axios后的目錄截圖如下:

聯系人頁面代碼(Index.cshtml):
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>聯系人管理</title> <link href="~/Content/bootstrap.css" rel="stylesheet" /> <script src="~/Scripts/vue.js"></script> <script src="~/Scripts/axios.js"></script> <style type="text/css"> table { margin: 10px auto auto 10px; } </style> </head> <body> <div id="app"> <table v-show="contactsList.length" class="table-condensed" border="1"> <thead class="navbar-header"> <tr> <th>姓名</th> <th>電話號碼</th> <th>Email地址</th> <th>操作</th> </tr> <tr v-for="(contact,index) in contactsList"> <td><input type="text" v-model="contact.Name" /></td> <td><input type="text" v-model="contact.PhoneNo" /></td> <td><input type="text" v-model="contact.EmailAddress" /></td> <td> <div v-if="contact.Id!=''"> <a href="#" v-on:click="updateContact(contact.Id,contact.Name,contact.PhoneNo,contact.EmailAddress)">修改</a> <a href="#" v-on:click="deleteContactById(contact.Id)">刪除</a> </div> <div v-else> <a href="#" v-on:click="addContact(contact.Name,contact.PhoneNo,contact.EmailAddress)">添加</a> </div> </td> </tr> </thead> </table> </div> <script type="text/javascript"> var vm = new Vue({ el: "#app", data: { contactsList:[] }, mounted() { this.getAllContacts(); }, methods: { getAllContacts: function () { axios.get('@Url.Action("Get", "Contact")' ).then( (response) => { this.contactsList = []; for (var i = 0; i < response.data.length; i++) { this.contactsList.push(response.data[i]); } this.contactsList.push({ Id:"", Name: "", PhoneNo: "", EmailAddress: "" }); }, (response) => { alert(response.status); } ).catch(function (response) { alert(response); }); }, addContact: function (name, phoneno, emailaddress) { axios.post('@Url.Action("Add", "Contact")', { contact: { Name: name, PhoneNo: phoneno, EmailAddress: emailaddress } }).then( (response) => { this.contactsList = []; for (var i = 0; i < response.data.length; i++) { this.contactsList.push(response.data[i]); } this.contactsList.push({ Id: "", Name: "", PhoneNo: "", EmailAddress: "" }); }, (response) => { alert(response.status); } ).catch(function (response) { alert(response); }); }, updateContact: function (id, name, phoneno, emailaddress) { axios.post('@Url.Action("Update", "Contact")', { contact: { Id: id, Name: name, PhoneNo: phoneno, EmailAddress: emailaddress} }).then( (response) => { this.contactsList = []; for (var i = 0; i < response.data.length; i++) { this.contactsList.push(response.data[i]); } this.contactsList.push({ Id: "", Name: "", PhoneNo: "", EmailAddress: "" }); }, (response) => { alert(response.status); } ).catch(function (response) { alert(response); }); }, deleteContactById: function (id) { axios.post('@Url.Action("Delete", "Contact")', { id: id }).then( (response) => { this.contactsList = []; for (var i = 0; i < response.data.length; i++) { this.contactsList.push(response.data[i]); } this.contactsList.push({ Id: "", Name: "", PhoneNo: "", EmailAddress: "" }); }, (response) => { alert(response.status); } ).catch(function (response) { alert(response); }); } } }); </script> </body> </html>
上述代碼有幾個需要說明的地方:
1、js部分:
a)我們將crud操作,封裝到了一個vue對象當中。
b)mounted方法涉及到vue對象的生命周期(限於篇幅,這里不展開),但要知道一點mounted方法一般會將ajax初始化數據操作放在其中。
c)axios插件的ajax請求操作(比如:get、post)可以看下相關的開發文檔,基本上看下例子就能上手開發。
2、html部分:
html部分用到了一些vue指令,比如v-for(遍歷對象列表)、v-if / v-else(條件判斷)、v-show(是否顯示,帶表達式)、v-model(模型綁定)。這部分知識是vue的核心知識,這里限於篇幅,不再細講。先基本會用即可。
總結:通過這個程序可以發現Vue的一個很大的優點,就是使用Vue后真正做到了所謂的前后端分離。前端頁面完全看不到夾渣的C#后端代碼,代碼顯示很干凈整潔。當然Vue還有其它優點,比如:相對容易學習(angular、react),虛擬dom、組件式開發,基於MVVM的數據雙向綁定,Vue.js文件很小,插件豐富、對應的阿里移動端Vue.js解決方案-weex等等,還是非常值得學習和應用的,怪不得當前Vue.js這么火熱。
最后有一個坑需要注意一下,就是js部分調用后台controller中的action時,傳遞參數是這樣的:
{ contact: { Id: id, Name: name, PhoneNo: phoneno, EmailAddress: emailaddress}
對應的Controller的Update方法是這樣的:
[HttpPost]
public JsonResult Update(Contact contact)
{
contactRepository.Post(contact);
return Json(contactRepository.Get());
}
其中的變量名,一定要一致,否則后台Controller中的Update方法接收不到前端頁面傳入的值。
代碼下載鏈接:https://pan.baidu.com/s/1EmJfwceYKiXZu0mPRCyXhQ 密碼:q9o3
