今早有分享一篇《創建Web API並使用》http://www.cnblogs.com/insus/p/7771428.html 接下來,我再分享一篇,怎樣在angularjs去呼叫Web API。 定義一個mode: using System; using System.Collections.G ...
今早有分享一篇《創建Web API並使用》http://www.cnblogs.com/insus/p/7771428.html 接下來,我再分享一篇,怎樣在angularjs去呼叫Web API。
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Insus.NET.Models { public class GarbageClassification { private string _ClassificationName; public string ClassificationName { get { return _ClassificationName; } set { _ClassificationName = value; } } } }Source Code
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Insus.NET.Models; namespace Insus.NET.Entities { public class DataEntity { public List<GarbageClassification> GetDatas() { return new List<GarbageClassification>(){ new GarbageClassification(){ ClassificationName="廢紙"}, new GarbageClassification(){ ClassificationName="塑料"}, new GarbageClassification(){ ClassificationName="玻璃"}, new GarbageClassification(){ ClassificationName="金屬物"}, new GarbageClassification(){ ClassificationName="布料"} }; } } }Source Code
如果你的數據是來自資料庫,那你需要修改這個實體類,修改其中的代碼,去資料庫讀取數據。
現在,我們需要創建Web API:
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using Insus.NET.Models; using Insus.NET.Entities; namespace Insus.NET.Apis { public class GarbageApiController : ApiController { [Route("api/GarbageApi/GetClassifications")] [HttpPost] public List<GarbageClassification> GetClassifications() { DataEntity de = new DataEntity(); return de.GetDatas(); } } }Source Code
OK,model,Entity和API均準備好了。下麵是在前端使用angularjs去呼叫剛纔寫好的API。
Html:
angularjs代碼,其實跟jQuery的ajax call差不多一樣:
var oApp = angular.module('GarbageApp', []) oApp.controller('GarbageCtrl', function ($scope, $http) { var obj = {}; $http({ method: 'POST', url: '/api/GarbageApi/GetClassifications', dataType: 'json', headers: { 'Content-Type': 'application/json; charset=utf-8' }, data: JSON.stringify(obj), }).then(function (response) { $scope.Classifications = response.data; }); });Source Code
演示(運行結果):