ITPub博客

首页 > IT职业 > IT职场 > angularjs呼叫Web API

angularjs呼叫Web API

IT职场 作者:yaoran 时间:2021-09-09 09:45:39 0 删除 编辑

 定义一个mode:

图片描述

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 GetDatas()        {            return new List(){                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 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


演示(运行结果):

图片描述

 

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1721/viewspace-2811863/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-04-15

  • 博文量
    112
  • 访问量
    593