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

来源:http://www.cnblogs.com/gester/archive/2016/04/24/5426190.html
-Advertisement-
Play Games

Here is what we want to do1. Create an ASP.NET Web service. This web service retrieves the data from SQL Server database table, returns it in JSON for ...



consuming asp.net web service in angularjs

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>

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 簡單工廠模式 -- 其本質就是由工廠類根據外部因素去選擇的創建一個實例。 簡單工廠模式模型:介面IProduct + 工廠類Creator 介面和實現類: 工廠類: 左瀟龍大神在博客裡面提到了簡單工廠的的一些實際應用,我學習一下。(http://www.cnblogs.com/zuoxiaolong ...
  • 學習要點: 1.巨幕組件 2.頁頭組件 3.縮略圖組件 4.警告框組件 主講教師:李炎恢 本節課我們主要學習一下 Bootstrap 的四個組件功能:巨幕組件、頁頭組件、縮略圖組件和警告框組件。 一.巨幕組件 巨幕組件主要是展示網站的關鍵性區域。 //在固定的範圍內,有圓角 //100%全屏,沒有圓 ...
  • 學習要點: 1.路徑組件 2.分頁組件 3.標簽組件 4.徽章組件 主講教師:李炎恢 本節課我們主要學習一下 Bootstrap 的四個組件功能:路徑組件、分頁組件、標簽組件和徽章組件。 一.路徑組件 路徑組件也叫做麵包屑導航。 //麵包屑導航 二.分頁組件 分頁組件可以提供帶有展示頁面的功能。 / ...
  • 學習要點: 1.輸入框組件 2.導航組件 3.導航條組件 主講教師:李炎恢 本節課我們主要學習一下Bootstrap的兩個個組件功能: 輸入框組件和導航導航條組件。 一.輸入框組件 文本輸入框就是可以在<input>元素前後加上文字或按鈕,可以實現對錶單控制項的擴展。 //在左側添加文字 //在右側添 ...
  • 學習要點: 1.小圖標組件 2.下拉菜單組件 3.按鈕組組件 4.按鈕式下拉菜單 主講教師:李炎恢 本節課我們主要學習一下 Bootstrap 的三個組件功能:小圖標組件、下拉菜單組件和各種按鈕組件。 一.小圖標組件 Bootstrap 提供了免費的 263 個小圖標(數了兩次),具體可以參考中文官 ...
  • 學習要點: 1.輔組類 2.響應式工具 主講教師:李炎恢 本節課我們主要學習一下 Bootstrap 的輔組類和響應式工具, 輔助類提供了一組類來輔組頁面設計,而響應式工具則利用媒體查詢顯示或隱藏某些內容。 一.輔助類 Bootstrap 在佈局方面提供了一些細小的輔組樣式,用於文字顏色以及背景色的 ...
  • 學習要點: 1.移動設備優先 2.佈局容器 3.柵格系統 主講教師:李炎恢 本節課我們主要學習一下 Bootstrap 的柵格系統,提供了一套響應式、移動設備優先的流式柵格系統。 一.移動設備優先 在 HTML5 的項目中,我們做了移動端的項目。它有一份非常重要的 meta,用於設置屏幕和設備等寬以 ...
  • In Angular there are several built in services. $http service is one of them. In this video, we will discuss another built in service, $log. It is als ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...