iT邦幫忙

2017 iT 邦幫忙鐵人賽
DAY 25
2
Cloud

Xamarin.Forms, ASP.NET Core WEB API搭配AZURE服務與資料庫服務整合應用實例系列 第 25

Day25 – Xamarin.Forms 與 ASP.NET CORE WEB API的資料傳遞

  • 分享至 

  • twitterImage
  •  

做完登入頁面後, 接下就是要製作主畫面, 從部署在Azure App Service的WEB API把資料撈回來呈現在畫面上, Xamarin.Forms要能呼叫WEB API, 需要Newtonsoft.Json與Microsoft.Net.Http這兩個套件, 所以在NuGet搜尋, 安裝在Portable專案
http://ithelp.ithome.com.tw/upload/images/20170107/20103333ZEVuuulhT6.png
http://ithelp.ithome.com.tw/upload/images/20170107/20103333nkF6HuyrOh.png

之後新增一個Models的資料夾, 建立一個SalesCheckIn.cs, 用來跟取回來的Json做對應
http://ithelp.ithome.com.tw/upload/images/20170107/20103333X2n62EH69U.png

然後打開config.cs, 新增一個WEB API連線位置如下
http://ithelp.ithome.com.tw/upload/images/20170107/20103333cKIsRobOwM.png

打開MainPage.xaml, 修改如下所示
http://ithelp.ithome.com.tw/upload/images/20170107/20103333IljrloSXrW.png

打開MainPage.xaml.cs, 修改如下所示
http://ithelp.ithome.com.tw/upload/images/20170107/20103333BYhqJbftC0.png
http://ithelp.ithome.com.tw/upload/images/20170107/20103333Eg2xvHjhi5.png

上述的程式碼中加入了Button_Clicked的事件, 按下時會跳出確認視窗, 並把Id與Locations顯示在視窗裡,接著就可以跑起來測試囉, 成功畫面如下
http://ithelp.ithome.com.tw/upload/images/20170107/20103333FVw63IRFfy.png

按下Detail按鈕
http://ithelp.ithome.com.tw/upload/images/20170107/201033330G30PFvjDs.png

以上打完收工

在實作的過程中, Xamarin.Forms有兩個不錯的特點: Binding跟ObservableCollection

Binding可以繫結前端UI的屬性與後端的Entity, 舉例來說底下的Lable的文字屬性直接對應到SalesCheckIn的Entity, 程式碼可以少寫很多

ObservableCollection在Xamarin.Forms裡, 可以用來存放資料Entity的集合, 很像WEB FORM Datatable, 加上Observable, 即應該是有實作Design Pattern中的觀察者模式 (Observer Pattern), 也就是說當Collection裡有發生變化時如新增或移除, 對應的View會跟著的連動.

後記: WEB API的叫用, 比起Web Service或是WCF簡潔許多, 難怪Restful會成為主流!


上一篇
Day24 - 業務人員行程管理系統開發IOS篇
下一篇
Day26 – Xamarin.Forms加入日曆控制項
系列文
Xamarin.Forms, ASP.NET Core WEB API搭配AZURE服務與資料庫服務整合應用實例32
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言