Part 17 Consuming ASP NET Web Service in AngularJS using $http

Here is what we want to do
1. Create an ASP.NET Web service. This web service retrieves the data from SQL Server database table, returns it in JSON formt.
2. Call the web service using AngularJS and display employee data on the web page

Step 1 : Create SQL Server table and insert employee data

Create table tblEmployees
(
    Id int primary key identity,
    Name nvarchar(50),
    Gender nvarchar(10),
    Salary int
)
Go

Insert into tblEmployees values (‘Ben‘, ‘Male‘, 55000)
Insert into tblEmployees values (‘Sara‘, ‘Female‘, 68000)
Insert into tblEmployees values (‘Mark‘, ‘Male‘, 57000)
Insert into tblEmployees values (‘Pam‘, ‘Female‘, 53000)
Insert into tblEmployees values (‘Todd‘, ‘Male‘, 60000)
Go

Step 2 : Create new empty asp.net web application project. Name it Demo.

Step 3 : Include the following settings in web.config file.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="DBCS"
         connectionString="server=.;database=SampleDB; integrated security=SSPI"/>
  </connectionStrings>
  <system.web>
    <webServices>
      <protocols>
        <add name="HttpGet"/>
      </protocols>
    </webServices>
  </system.web>
</configuration>

Step 4 : Add a class file to the project. Name it Employee.cs. Copy and paste the following code.

namespace Demo
{
    public class Employee
    {
        public int id { get; set; }
        public string name { get; set; }
        public string gender { get; set; }
        public int salary { get; set; }
    }
}

Step 5 : Add a new WebService (ASMX). Name it EmployeeService.asmx. Copy and paste the following code.

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
using System.Web.Services;

namespace Demo
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    public class EmployeeService : System.Web.Services.WebService
    {
        [WebMethod]
        public void GetAllEmployees()
        {
            List<Employee> listEmployees = new List<Employee>();

            string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
            using (SqlConnection con = new SqlConnection(cs))
            {
                SqlCommand cmd = new SqlCommand("Select * from tblEmployees", con);
                con.Open();
                SqlDataReader rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    Employee employee = new Employee();
                    employee.id = Convert.ToInt32(rdr["Id"]);
                    employee.name = rdr["Name"].ToString();
                    employee.gender = rdr["Gender"].ToString();
                    employee.salary = Convert.ToInt32(rdr["Salary"]);
                    listEmployees.Add(employee);
                }
            }

            JavaScriptSerializer js = new JavaScriptSerializer();
            Context.Response.Write(js.Serialize(listEmployees));
        }
    }
}

Step 6 : Add a new folder to the project. Name it Scripts. Download angular.js script file from http://angularjs.org, and past it in Scripts folder.

Step 7 : Add a new JavaScript file to the Scripts folder. Name it Script.js. Copy and paste the following code.

/// <reference path="angular.min.js" />

var app = angular
        .module("myModule", [])
        .controller("myController", function ($scope, $http) {

            $http.get("EmployeeService.asmx/GetAllEmployees")
                 .then(function (response) {
                     $scope.employees = response.data;
                 });
        });

Step 8 : Add a new stylesheet to the project. Name it Styles.css. Copy and paste the following styles in it.

body {
    font-family: Arial;
}

table {
    border-collapse: collapse;
}

td {
    border: 1px solid black;
    padding: 5px;
}

th {
    border: 1px solid black;
    padding: 5px;
    text-align: left;
}

Step 9 : Add an HTML page to the ASP.NET project. Copy and paste the following HTML and Angular code

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Scripts/angular.js"></script>
    <script src="Scripts/Script.js"></script>
    <link href="Styles.css" rel="stylesheet" />
</head>
<body ng-app="myModule">
    <div ng-controller="myController">
        <table>
            <thead>
                <tr>
                    <th>Id</th>
                    <th>Name</th>
                    <th>Gender</th>
                    <th>Salary</th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="employee in employees">
                    <td>{{employee.id}}</td>
                    <td>{{employee.name}}</td>
                    <td>{{employee.gender}}</td>
                    <td>{{employee.salary}}</td>
                </tr>
            </tbody>
        </table>
    </div>
</body>
</html>
时间: 2024-12-26 03:17:34

Part 17 Consuming ASP NET Web Service in AngularJS using $http的相关文章

HYAppFrame数据库开发入门(ASP.NET Web Service)

本节主要讲解服务器端ASP.NET Web Service数据库配置和操作,客户端数据库操作. HYAppFrame项目地址:https://sourceforge.net/u/chinahysoft/profile/ 1.    服务器端数据库操作 HYAppFrame服务器端通过ASP.NET Web Service连接数据库. 数据库连接配置 在文件Web.config配置数据库,需设置数据库服务器地址Data Source.数据库名称Initial Catalog.访问帐号User Id

在 Visual Studio 2010 中创建 ASP.Net Web Service

第一步:创建一个“ASP.Net Empty Web Application”项目 第二步:在项目中添加“Web Service”新项目 第一步之后,Visual Studio 2010会创建一个仅含一个站点配制文件(Web.config)的空站点,其余的什么也没有. 我们在Visual Studio 2010的Solution Explorer中,选中当前的这个project,添加新项目(右键菜单:Add --> New Item),选择“Web Service”这种类型: 看到这里读者应该就

ASP.NET Web Service中使用Session 及 Session丢失解决方法 续

原文:ASP.NET Web Service中使用Session 及 Session丢失解决方法 续 1.关于Session丢失问题的说明汇总,参考这里 2.在Web Servcie中使用Session,需要对Web Method做如下处理 [WebMethod(EnableSession = true)]public void usingSession(){    Session["Name"] = "Name";} 如果不加EnableSession = tru

Win Form + ASP.NET Web Service 文件上传下载--HYAppFrame

本章节主要讲解HYAppFrame服务器端如何ASP.NET Web Service实现文件(含大文件)上传,WinForm客户端如何下载文件. 1    服务器端文件上传 1.1 上传文件 函数FileUpload(stringfileFullPath, byte[] file)用于上传文件,生成文件前检查文件路径所在文件夹是否存在,不存在则首先创建文件夹. [WebMethod(EnableSession = true,Description = "上传文件")] public i

微软实战训练营(X)重点班第(1)课:SOA必备知识之ASP.NET Web Service开发实战

微软实战训练营 上海交大(A)实验班.(X)重点班 内部课程资料 链接:http://pan.baidu.com/s/1jGsTjq2 密码:0wmf <微软实战训练营(X)重点班第(1)课:SOA必备知识之ASP.NET Web Service开发实战>微软实战训练营 上海交大(A)实验班.(X)重点班 .(E)英语口语班http://54peixun.com/MSTrainingCamp/index.html 微软实战训练营(X)重点班第(1)课:SOA必备知识之ASP.NET Web S

Silverlight 2 (beta1)数据操作(2)——使用ASP.NET Web Service进行数据CRUD操作(下)

前台界面 后台代码 //按钮事件 void saveButton_Click(object sender, RoutedEventArgs e) { if (userName.Text.Trim() == string.Empty) { errMessage.Foreground = new SolidColorBrush(Colors.Red); errMessage.Text = "请输入用户名称!"; errMessage.Visibility = Visibility.Visi

Silverlight 2 (beta1)数据操作(1)——使用ASP.NET Web Service进行数据CRUD操作(上)

目录 导言 软件需求 在SQL 2005中创建数据库 在Visual Studio 2008中创建 Silverlight 2 (beta1)工程 在ASP.NET工程里创建Web Service 在Silverlight 2 (beta1)工程中引用ASP.NET Web Service 添加数据部分 查询数据部分 修改数据部分 删除数据部分 整合程序 结语 例子下载 导言 Silverlight 2支持JSON.Web Service.WCF以及Sockets等新特性对数据CRUD操作,这个

sharepoint 2010 创建自定义的ASP.NET Web Service (上)

项目背景 根据客户需求在SharePoint 2010 中创建自定义的ASP.NET Web Service可以分为3种方式(我所知道的).废话少说,下面一一列举: 创建方式 MSDN 官方博客自己的一个创建ASP.NET Web Service.http://msdn.microsoft.com/zh-cn/library/ms464040(v=office.14).aspx 但是它不推荐这种方式. 通过创建类库项目,使类库项目包装webservice. MSDN推荐使用的方式,通过WCF创建

Error in WCF client consuming Axis 2 web service with WS-Security UsernameToken PasswordDigest authentication scheme

13down votefavorite 6 I have a WCF client connecting to a Java based Axis2 web service (outside my control). It is about to have WS-Security applied to it, and I need to fix the .NET client. However, I am struggling to provide the correct authenticat