ASP。使用Angular2和WEB API插入/选择数据库

介绍 在我们之前的文章中, ASP。NET Core 1.0 RC2和Angular2使用WEB API 我们已经详细了解了ASP。NET Core 1.0, Angular2和WEB API来显示数据。 在本文中,我们将详细介绍如何使用ASP。NET Core 1.0与Angular2插入和选择学生细节到SQL Server数据库使用WEB API。 在本文中,我们将详细了解如何, 创建我们的ASP。NET Core 1.0 RC2 Web应用程序。创建模型以添加学生详细信息。使用实体框架创建WEB API控制器来选择和插入数据到数据库。如何添加TypeScript JSON配置文件如何添加grunt包使用NPM配置文件如何配置grunt文件。如何创建我们的Angular2应用程序,启动使用类型脚本文件。使用HTTP Get/Post插入和选择数据从Angular2到WEB API插入到DB。创建HTML文件如何运行Grunt文件使用Visual Studio任务运行器浏览器如何运行和查看我们的示例。 参考网站: 教程:英雄指南http客户端 先决条件 Visual Studio 2015:你可以从这里下载。ASP。NET Core 1.0 RC2:下载链接,link2。 使用的代码 我们将使用SQL Server数据库作为WEB API。首先,我们创建一个名为StudentsDB的数据库和一个名为StudentMaster的表。下面是用于在表中创建数据库表和示例记录插入查询的SQL脚本。在本地SQL服务器中运行以下查询,以创建在out项目中使用的数据库和表。 隐藏,收缩,复制Code

USE MASTER 
GO 
 
-- 1) Check for the Database Exists .If the database is exist then drop and create new DB 
IF EXISTS (SELECT [name] FROM sys.databases WHERE [name] = 'StudentsDB' ) 
DROP DATABASE StudentsDB 
GO 
 
CREATE DATABASE StudentsDB 
GO 
 
USE StudentsDB 
GO 
 
 
-- 1) //////////// StudentMasters 
 
IF EXISTS ( SELECT [name] FROM sys.tables WHERE [name] = 'StudentMasters' ) 
DROP TABLE StudentMasters 
GO 
 
CREATE TABLE [dbo].[StudentMasters]( 
        [StdID] INT IDENTITY PRIMARY KEY, 
        [StdName] [varchar](100) NOT NULL,    
        [Email]  [varchar](100) NOT NULL,    
        [Phone]  [varchar](20) NOT NULL,    
        [Address]  [varchar](200) NOT NULL 
) 
 
-- insert sample data to Student Master table 
INSERT INTO [StudentMasters]   ([StdName],[Email],[Phone],[Address]) 
     VALUES ('Shanu','syedshanumcain@gmail.com','01030550007','Madurai,India') 
 
INSERT INTO [StudentMasters]   ([StdName],[Email],[Phone],[Address]) 
     VALUES ('Afraz','Afraz@afrazmail.com','01030550006','Madurai,India') 
      
INSERT INTO [StudentMasters]   ([StdName],[Email],[Phone],[Address]) 
     VALUES ('Afreen','Afreen@afreenmail.com','01030550005','Madurai,India') 
      
      
     select * from [StudentMasters]

步骤1:创建我们的ASP。NET Core 1.0 Web应用程序。 在安装了Visual Studio 2015和ASP之后。NET Core 1.0 RC2。单击“开始”,然后单击“程序”并选择Visual Studio 2015——单击“新建”,然后单击“项目”,选择Web并选择ASP。NET Core Web应用程序。输入项目名称并单击OK。 接下来选择Web Application。如果您没有在云中托管,那么您可以取消勾选右下角的云中的主机。单击OK 现在我们有 数据库连接字符串: 现在我们需要更改本地连接字符串从ASP。Net 5项目与我们的SQL服务器连接。 注意:在ASP。我们需要使用“appsettings”。json文件而不是web.config文件。我们可以找到“appsettings”。"文件从我们的ASP。NET Core 1.0解决方案。 要用SQL连接更改默认连接字符串,请打开“appsettings”。是的,这是json文件,这个文件在默认情况下看起来像下图。 默认的connectionstring是这样的 隐藏,复制Code

"ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-Core1.0Angular2CRUDInsert-599f2ca4-119a-4fd5-a2a4-e58fb4b2e5be;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
Now we change this to our SQL Connection like below,
"ConnectionStrings": {
    "DefaultConnection": "Server=SQLSERVERNAME;Database=StudentsDB;user id=SQLID;password=SQLPWD;Trusted_Connection=True;MultipleActiveResultSets=true;"
  },

步骤2:创建MVC模型来返回学生列表 我们可以通过在模型文件夹中添加一个新的类文件来创建模型。 右键点击模型文件夹并点击新建项目。选择类并输入你的类名为“studentmaster .cs” 在这个类中,我们首先创建属性变量,add student。我们将在我们的WEB API控制器中使用它。 隐藏,复制Code

using System.ComponentModel.DataAnnotations;
namespace WebApplicationTestSample.Models
{
    public class StudentMasters
    {
        [Key]
        public int StdID { get; set; }

        [Required]
        [Display(Name = "Name")]
        public string StdName { get; set; }

        [Required]
        [Display(Name = "Email")]
        public string Email { get; set; }

        [Required]
        [Display(Name = "Phone")]
        public string Phone { get; set; }

        public string Address { get; set; }

    }
}

步骤3:创建WEB API控制器 我们可以通过在控制器文件夹中添加一个新的空API控制器来创建控制器。 右键单击Controller文件夹并添加Controller .选择API Controller with action,使用Entity Framework并单击Add 选择模型类为StudentMasters。 选择模型类之后,选择数据上下文类。这里我们选择默认的ApplicationDbContext。注意,我们已经将默认连接字符串设置为SQL Server数据库连接。接下来将我们的WEB API控制器命名为StudentMastersAPI。 我们可以看到,我们的WEB API控制器现在已经创建,并且控制器将包含默认的Select (HttpGet)和Insert方法as (HttpPost)。我们将在我们的Angular2中使用这个get和post方法来选择和插入数据到数据库。 为了测试它,我们可以运行我们的项目并复制get方法的api路径这里我们可以看到get的api路径是api/StudentMastersAPI/ 运行程序并粘贴上面的API路径来测试我们的输出。 步骤4:如何添加TypeScript JSON配置文件 TypeScript JSON文件将指定根文件和编译项目所需的编译器选项。要了解更多关于TypeScript JSON配置,请访问这个网站 http://www.typescriptlang.org/docs/handbook/tsconfig-json.html, 要创建TypeScript JSON文件,右键单击您的项目并单击Add new Item。 选择TypeScript JSCON配置文件并单击ok。文件将看起来像下图。 现在复制下面的代码并用配置文件替换。 隐藏,复制Code

"compilerOptions": {
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "module": "commonjs",
    "moduleResolution": "node",
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "target": "es5",
 "sourceMap": true

步骤5:如何使用NPM配置文件添加grunt包 现在我们需要添加一个NPM配置文件,以添加一个运行java脚本的grunt包。 由于我们已经创建了一个Web应用程序,NPM配置文件将位于我们的项目中。 默认情况下,我们不能view我们的NPM配置文件。NPM配置文件的名称为“package”。JSON”。要从解决方案资源管理器查看,请单击“显示所有文件” 现在打开“包”。现在,首先我们需要更改名称为我们的项目解决方案的名称,并添加我们的grunt包,我们可以看到下面的代码。 在这里,我们更改了名称作为解决方案名称,并添加了grunt包。 隐藏,复制Code

{
  "name": "test",
  "version": "0.0.0",
  "private": true,
"devDependencies": {
    "grunt": "1.0.1",
    "grunt-contrib-copy": "1.0.0",
    "grunt-contrib-uglify": "1.0.1",
    "grunt-contrib-watch": "1.0.0",
    "grunt-ts": "5.5.1",
    "gulp": "3.8.11",
    "gulp-concat": "2.5.2",
    "gulp-cssmin": "0.1.7",
    "gulp-uglify": "1.2.0",
    "rimraf": "2.2.8"
  }
}

现在保存包。json文件,您应该能够看到一个grunt包下的Dependencies/ npm文件夹将首先采取,然后安装。 恢复: 所有的安装: 步骤6:配置Grunt文件。 Grunt用于为我们的项目构建所有客户端资源,比如JavaScript。 第一步是将Grunt文件添加到我们的项目中。右键单击我们的项目,选择Grunt配置文件,然后单击Add。 在创建文件之后,现在我们需要编辑这个文件来添加加载插件,配置插件和定义任务 在我们的Grunt文件中,我们有我们在npm中添加的第一个加载插件。使用loadNpmTask我们加载'咕哝-contrib-copy '咕哝-contrib-uglify'咕哝-contrib-watch' 接下来配置grunt文件,将app.js文件添加到wwwroot文件夹中。所有来自Scripts文件夹的脚本文件都将添加到这个app.js文件中。接下来我们需要将所有的脚本文件从'node_modules/复制到我们的本地js文件夹中。 手表插件将用于检查JavaScript文件的任何变化,并更新它的app.js与所有新的变化。 隐藏,收缩,复制Code

/*
This file in the main entry point for defining grunt tasks and using grunt plugins.
Click here to learn more. http://go.microsoft.com/fwlink/?LinkID=513275&clcid=0x409
*/
module.exports = function (grunt) {
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-ts');
    grunt.initConfig({
        ts:
        {
            base:
            {
                src: ['Scripts/app/boot.ts', 'Scripts/app/**/*.ts'],
                outDir: 'wwwroot/app',
                tsconfig: './tsconfig.json'
            }
        },
        uglify:
        {
            my_target:
            {
                files: [{
                    expand: true,
                    cwd: 'wwwroot/app',
                    src: ['**/*.js'],
                    dest: 'wwwroot/app'
                }]
            },
            options:
            {
                sourceMap: true
            }
        },
        // Copy all JS files from external libraries and required NPM packages to wwwroot/js  
        copy: {
            main: {
                files:
                     [{
                         expand: true,
                         flatten: true,
                         src: ['Scripts/js/**/*.js', 'node_modules/es6-shim/es6-shim.min.js', 'node_modules/systemjs/dist/system-polyfills.js', 'node_modules/angular2/bundles/angular2-polyfills.js', 'node_modules/systemjs/dist/system.src.js', 'node_modules/rxjs/bundles/Rx.js', 'node_modules/angular2/bundles/angular2.dev.js'],
                         dest: 'wwwroot/js/',
                         filter: 'isFile'
                     }]
            }
        },
        // Watch specified files and define what to do upon file changes  
        watch: {
            scripts: {
                files: ['Scripts/**/*.js'],
                tasks: ['ts', 'uglify', 'copy']
            }
        }
    });
    // Define the default task so it will launch all other tasks  
    grunt.registerTask('default', ['ts', 'uglify', 'copy', 'watch']);
};

第7步:添加依赖来安装Angular2和所有其他文件 我们使用NPM在web应用程序中安装Angular2。打开我们的包。JSON文件和下面的依赖关系。 隐藏,复制Code

"dependencies": {
    "@angular/http": "2.0.0-rc.1",
    "angular2": "^2.0.0-beta.8",
    "angular2-jwt": "0.1.16",
    "angular2-meteor": "0.5.5",
    "cors": "2.7.1",
    "systemjs": "0.19.22",
    "es6-promise": "^3.0.2",
    "es6-shim": "^0.33.3",
    "reflect-metadata": "0.1.2",
    "rxjs": "5.0.0-beta.2",
    "tsd": "^0.6.5",
    "zone.js": "0.5.15"
  },

编辑包。json文件将看起来像下图。 保存文件,等待几秒钟,以完成所有正派安装。 步骤8如何创建我们的Angular2应用程序,启动使用类型脚本文件。 现在是创建Angular2应用程序的时候了。首先创建一个名为Scripts的文件夹。右键点击我们的项目,点击添加新文件夹,并将文件夹命名为“Scripts”。现在我们将在这个脚本文件夹中创建TypeScript文件。 要使用Angular2,我们需要创建2个重要的TypeScript文件。 组件文件,我们写Angular代码的地方。启动文件:运行我们的组件应用程序。 创建App TypeScript文件: 右键单击Scripts文件夹,然后单击add new Item。选择TypeScript文件并将该文件命名为App.ts,然后单击Add。 在App.ts文件中,我们有三个部分,首先是 导入部分接下来是组件部分接下来是用于编写业务逻辑的类。 在这里,我们可以看到一个简单的基本单向绑定示例,用于在h1边标签中显示欢迎消息。 1. 导入部分:首先我们导入angular2文件在我们的组件使用我们在angular2进口http使用http客户端组件和进口NgFor使用循环和绑定的所有学生细节数组值一个接一个,我们也进口一个打印稿出口类名StudentMasters模型文件。 隐藏,复制Code

import { Component, Injectable, Inject} from 'angular2/core';
import { NgIf, NgFor } from 'angular2/common';
import {Http, Response, HTTP_PROVIDERS, Headers, RequestOptions} from 'angular2/http';
import { StudentMasters } from './model';
import {Observable} from 'rxjs/Observable';
import 'rxjs/Rx';

2.接下来是组成部分: 组件中有选择器、指令和模板。Selector是给这个应用程序命名,在html文件中,我们使用这个选择器名称来显示在html页面中。 在模板中我们编写代码。在模板中,我们首先创建一个表单,使用http post方法将学生详细信息插入数据库。在按钮单击中,我们调用addStudentsDetails()方法来插入学生的详细信息。插入之后,我们调用getData()方法来绑定更新后的结果。 为了显示StudentMaster的详细信息,我们在html表格中使用了ngFOR。在该方法中,我们使用http get函数从WEB API加载数据并显示在html页面中。我们已经在模板里面做了所有的设计。还有另一种方法,我们可以创建一个html文件,并在该html页面和模板中添加所有设计,我们可以给html文件名。 隐藏,收缩,复制Code

@Component({
    selector: "my-app",
    directives: [NgFor],
    template: `     
<tablestyle="background-color:#FFFFFF; border: dashed 3px #6D7B8D; padding :5px;width :99%;table-layout:fixed;"cellpadding="2"cellspacing="2">
                    <trstyle="height: 30px; background-color:#336699 ; color:#FFFFFF ;border: solid 1px #659EC7;">
                    
                  <td>
                      <h2>Insert Student Details : </h2>
                  </td>
            </tr>
        <tr>
        <td>
 <tablestyle="color:#9F000F;font-size:large"cellpadding="4"cellspacing="6">
 <tr>
     <td><b>Students ID: </b> </td>
    <td>
      <input[(ngModel)]="students.StdID"value="0"style="background-color:tan"readonly>
  </td>
  <td><b>Students Name: </b> </td>
    <td>
    <input[(ngModel)]="students.StdName">
  </td>
</tr>
 <tr>
     <td><b>Email: </b> </td>
    <td>
      <input[(ngModel)]="students.Email">
  </td>
  <td><b>Phone: </b> </td>
    <td>
    <input[(ngModel)]="students.Phone">
  </td>
</tr>
<tr>
     <td><b>Address: </b> </td>
    <td>
     <input[(ngModel)]="students.Address">
  </td>
  <tdcolspan="2">
<button(click)=addStudentsDetails() style="background-color:#334668;color:#FFFFFF;font-size:large;width:200px;
                              border-color:#a2aabe;border-style:dashed;border-width:2px;">Save</button>
   </td>
   </tr>
   </table>
 </td>
</tr>

<tr><td>&nbsp; </td></tr>

 <tr>
        <td>
 <tablestyle="background-color:#FFFFFF; border solid 2px #6D7B8D; padding 5px;width 99%;table-layout:fixed;"cellpadding="2"cellspacing="2">

                                <trstyle="height: 30px; background-color:#336699 ; color:#FFFFFF ;border: solid 1px #659EC7;">
                                    <tdwidth="100"align="center">Student ID</td>
                                    <tdwidth="240"align="center">Student Name</td>
                                    <tdwidth="240"align="center">Email</td>
                                    <tdwidth="120"align="center">Phone</td>
                                    <tdwidth="340"align="center">Address</td>
                                    

                                </tr>
                                <tbody*ngFor="let std of student">
                                    <tr>

                                        <tdalign="center"style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">
                                            <spanstyle="color:#9F000F">{{std.StdID}}</span>
                                        </td>

                                        <tdalign="left"style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">
                                            <spanstyle="color:#9F000F">{{std.StdName}}</span>
                                        </td>

                                        <tdalign="left"style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">
                                            <spanstyle="color:#9F000F">{{std.Email}}</span>
                                        </td>

                                        <tdalign="center"style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">
                                            <spanstyle="color:#9F000F">{{std.Phone}}</span>
                                        </td>

                                        <tdalign="left"style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">
                                            <spanstyle="color:#9F000F">{{std.Address}}</span>
                                        </td>
                                      
                                    </tr>
                                </tbody>
                            </table>
</td>
</tr>
</table>
              `,

})

3.出口类: 这是我们在组件模板中执行所有业务逻辑和变量声明的主要类。在这个类中,我们创建了一个名为getData()的方法,在这个方法中,我们获得API方法结果并将结果绑定到student数组。在单击按钮时,我们调用addStudentsDetails()方法来使用http post方法将数据插入数据库。 隐藏,收缩,复制Code

 export class AppComponent {
    student: Array<StudentMasters> = []; 
    students = {};
    myName: string;  
    constructor(@Inject(Http) public http: Http) {
        this.myName = "Shanu";      
        this.getData();       
    }

    getData() {         
        this.http.get('api/StudentMastersAPI')
            .map((responseData) => {
                return responseData.json();
            })
            .map((student: Array<any>) => {
                let result: Array<StudentMasters> = [];
                if (student) {
                    student.forEach((student) => {
                        result.push(new StudentMasters(student.StdID, student.StdName,
                            student.Email, student.Phone, student.Address));
                    });
                }
                return result;
            }) 
            .subscribe(res => this.student = res);
    }

    addStudentsDetails() {     
        var headers = new Headers();
        headers.append('Content-Type', 'application/json; charset=utf-8');
        this.http.post('api/StudentMastersAPI', JSON.stringify(this.students), { headers: headers }).subscribe();
        alert("Student Detail Inserted");
        this.getData();       
    }    
}

接下来,我们需要添加引导。ts文件来运行我们的应用程序。 创建启动TypeScript文件: 右键单击Scripts文件夹,然后单击add new Item。选择TypeScript文件并将该文件命名为boot。点击添加。 在引导。我们在ts文件中添加以下代码。这里首先我们导入bootsrap文件来加载和运行我们的应用程序文件,同时我们也导入我们的应用组件。注意,要导入我们的应用程序,我们需要给相同的类名我们的应用typescript文件,并将应用路径设为from ”。接下来,通过在bootstrap中添加应用名bootstrap(myAppComponent);运行应用程序。 隐藏,复制Code

///<reference path="../node_modules/angular2/typings/browser.d.ts" />  

import {bootstrap} from 'angular2/platform/browser'
import {ROUTER_PROVIDERS} from "angular2/router";
import {HTTP_PROVIDERS, HTTP_BINDINGS} from "angular2/http";
import {AppComponent} from './app'

bootstrap(AppComponent, [HTTP_BINDINGS, HTTP_PROVIDERS]);

创建模型TypeScript文件: 右键单击Scripts文件夹,然后单击add new Item。选择TypeScript文件并将该文件命名为model。点击添加。 我们使用这个模型typescript文件来创建我们的Studentmasters模型,并声明我们在MVC模型中创建的所有公共属性。 隐藏,复制Code

export class StudentMasters {
    constructor(
        public StdID: number,
        public StdName: string,
        public Email: string,
        public Phone: string,
        public Address: string
    ) { }
}

步骤9:创建HTML文件 接下来,我们需要创建html页面来查看结果。要添加HTML文件,右键单击wwwroot文件夹,然后单击添加新项目,将名称命名为index.html,然后单击添加。 在HTMl文件中替换以下代码。这里我们可以看到,首先在头部分,我们添加了所有的脚本引用文件,在脚本中,我们加载我们的引导文件来运行我们的应用程序。在主体部分,我们使用组件选择器的名称显示结果。在我们的应用程序组件,我们给选择器的名称为“myapp1”。在这个HTML中,我们添加了这样的标签来显示结果:my-app>Please wait… 隐藏,收缩,复制Code

<html>
<head>
    <title>ASP.NET Core: AngularJS 2 Demo</title>
    <metaname="viewport"content="width=device-width, initial-scale=1">
    <!-- 1. Load libraries -->
    <!-- IE required polyfills -->
    <scriptsrc="/js/es6-shim.min.js"></script>
    <scriptsrc="/js/system-polyfills.js"></script>
    <!-- Angular2 libraries -->
    <scriptsrc="/js/angular2-polyfills.js"></script>
    <scriptsrc="/js/system.src.js"></script>
    <scriptsrc="/js/Rx.js"></script>
    <scriptsrc="/js/angular2.dev.js"></script>
    <scriptsrc="/js/router.dev.js"></script>
    <scriptsrc="/js/http.dev.js"></script>
    <!-- Bootstrap via SystemJS -->
    <script>

        System.config
        ({
            packages:
            {
                "app":
                {
                    defaultExtension: 'js'
                },
                'lib': { defaultExtension: 'js' }
            }
        });
        System.import('app/boot').then(null, console.error.bind(console));
    </script>
</head>

<body>

    <tablestyle='width: 99%;table-layout:fixed;'>
        <tr>
            <td>
                <tablestyle="background-color:#FFFFFF;border: dashed 3px #6D7B8D; padding:10px;width: 99%;table-layout:fixed;"cellpadding="12"cellspacing="12">
                    <trstyle="height: 30px; background-color:#f06a0a ; color:#FFFFFF ;border: solid 1px #659EC7;">
                        <tdalign="center">
                            <h3> SHANU ASP.NET Core1.0 Insert/Select Student Details to Database Using Angular2 and WEB API </h3>
                        </td>
                    </tr>  
                </table>

            </td>
        </tr>
        
        <tr>
            <td>

                <!-- Application PlaceHolder -->
                <my-app>Please wait...</my-app>
            </td>
        </tr>
        </table>

</body>
</html> 

那么接下来我们已经成功创建了我们的第一个Angular2和Asp。Net core 1.0 web应用程序和等待我们必须再做一个挂起的工作来运行我们的应用程序?是的,我们需要运行我们的Grunt文件来创建我们的整个脚本文件在我们的wwwroot脚本文件夹。 步骤8:使用Visual Studio任务运行器资源管理器运行Grunt文件 现在我们需要使用Visual Studio任务运行器运行Grunt文件。 要查看任务运行器,请单击“菜单查看”->其他窗口,→然后单击任务运行器资源管理器。 我们也可以通过在解决方案资源管理器中右键单击Gruntfile.js打开任务运行器,然后单击任务运行器资源管理器。 现在我们可以看到任务运行器资源管理器。 单击GruntFile.js并单击左上角的refresh按钮。 现在我们可以看到所有的GruntFile都被添加了。 右键单击别名任务下的默认值,然后单击Run。 现在我们的Grunt文件已经在我们的项目中成功运行。当我们添加一个脚本文件时,我们可以看到新的app.js文件将在我们的wwwroot文件夹中创建。 运行程序: 在这里,我们可以看到所有来自WEB API的数据已经使用Angular2绑定到我们的HTML页面。您可以插入新的学生详细信息。与此相同,您可以添加Update和Delete函数来执行完整的CRUD操作来维护学生记录。 注意:首先在SQL服务器中创建数据库和表,您可以运行本文中的SQL脚本创建StudentsDB数据库和studentmaster表,同时不要忘记更改连接字符串“appsettings.json” 历史 Core1Angular2CRUDTest.zip——2016/08/06 本文转载于:http://www.diyabc.com/frontweb/news17326.html

posted @ 2020-08-13 02:16  Dincat  阅读(201)  评论(0编辑  收藏  举报