本文转自:http://www.c-sharpcorner.com/article/using-mvc-6-and-angularjs-2-with-net-core/

In this article,

  1. Setup Environment.
  2. Overview on ASP.NET.
  3. Start with .NET Core 1.0.
  4. Explore Initial Template (Empty).
  5. How to Add MVC6.
  6. AngularJS2.
    • Manage Client-side Dependencies.
    • Use Package Manager (NPM).
    • Use Task Runner.
    • Bootstrapping, using Type Script
  7. Build & run Application

Setup Environment
Prerequisites: The following prerequisites are needed.

  1. Visual Studio 2015
  2. ASP.NET Core 1.0

Visual Studio 2015: If you already have a copy of Visual Studio 2015 installed, you may update Visual Studio 2015 with Update 3. Or Download Visual Studio Community 2015 for free.
.NET Core Downloads:
You may download one of these:

  1. .NET Core SDK (Software Development Kit/Command Line Interface) tools.
  2. .NET Core 1.0.0 - VS 2015 Tooling Preview 2 (Run apps with the .NET Core runtime).

We are all set to go. Before we dive into our main topic, let’s get an overview on ASP.NET.
Overview on ASP.NET
Let’s differentiate both.
.NET Framework

  1. Developed and run on Windows platform only.
  2. Built on the .NET Framework runtime.
  3. Supported (MVC, Web API & SignalR) Dependency Injection (DI).
  4. MVC & Web API Controller are separated.

.Net Core

  1. Open Source.
  2. Developed & run on Cross Platform.
  3. Built on the .NET Core runtime & also on .NET Framework.
  4. Facility of dynamic compilation.
  5. Built in Dependency Injection (DI).
  6. MVC & Web API Controller are unified, Inherited from same base class.
  7. Smart tooling (Bower, NPM, Grunt & Gulp).
  8. Command-line tools.

Start with .NET Core 1.0
Let’s create a new project with Visual Studio 2015 > File > New > Project.

Choose empty template and click OK.

Visual Studio will create a new project of ASP.NET Core empty project.

We will now explore all initial files one by one.
Explore Initial Template
Those marked from Solution Explorer are going to be explored, one by one.

First of all, we know about program.cs file. Let’s concentrate on it.
Program.cs: Here, we have sample piece of code. Let’s get explanation.

  1. namespace CoreMVCAngular
  2. {
  3. public class Program
  4. {
  5. public static void Main(string[] args) {
  6. var host = new WebHostBuilder().UseKestrel().UseContentRoot(Directory.GetCurrentDirectory()).UseIISIntegration().UseStartup < Startup > ().Build();
  7. host.Run();
  8. }
  9. }
  10. }

.UseKestrel() : Define the Web Server. ASP.NET Core supports hosting in IIS and IIS Express.
HTTP servers

  1. Microsoft.AspNetCore.Server.Kestrel (cross-platform)
  2. Microsoft.AspNetCore.Server.WebListener (Windows-only)

.UseContentRoot(Directory.GetCurrentDirectory()) : Application base path that specifies the path to the root directory of the Application. .UseIISIntegration(): For hosting in IIS and IIS Express. .UseStartup<Startup>() : Specifies the Startup class. .Build() : Build the IWebHost, which will host the app & manage incoming HTTP requests.
Startup.cs
This is the entry point of every .NET Core Application. It provides services, that the Application required.

  1. namespace CoreMVCAngular
  2. {
  3. public class Startup
  4. {
  5. // This method gets called by the runtime. Use this method to add services to the container.
  6. // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
  7. public void ConfigureServices(IServiceCollection services) {}
  8. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  9. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {}
  10. }
  11. }

As you can see, there are two methods; one is ConfigureServices & another is Configure. In Configure method, three parameters are specified.
IApplicationBuilder defines a class, which provides the mechanisms to configure an Application's request.
We can add MVC (middleware) to the request pipeline by using “Use” extension method. Later, we will use it. ConfigureServices is an extension method, which is configured to use the several services.
Project.json: This is where our Application dependencies are listed i.e by name & version. This file also manages runtime, compilation settings. Dependencies: All Application dependencies can add new dependencies, if required, intellisense will help up to include with the name & version.

After saving changes, it will automatically restore the dependencies from NuGet.

Here, the code snippet is changed.

  1. "dependencies": {
  2. "Microsoft.NETCore.App": {
  3. "version": "1.0.0",
  4. "type": "platform"
  5. },
  6. "Microsoft.AspNetCore.Diagnostics": "1.0.0",
  7. "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
  8. "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
  9. "Microsoft.Extensions.Logging.Console": "1.0.0",
  10. "Microsoft.AspNetCore.Mvc": "1.0.0"
  11. },

To uninstall, go to Solution explorer > right click on package > Uninstall package.

Tools: This section manages and lists command line tools. We can see IISIntegration.Tools is added by default, which is a tool that contains dotnet publish iis command for publishing the Application on IIS.

  1. "tools": {
  2. "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
  3. },

Frameworks: As we can see, initially our app is running on the .NET Core platform by default with the runtime.

  1. “netcoreapp1 .0”.
  2. "frameworks": {
  3. "netcoreapp1.0": {
  4. "imports": ["dotnet5.6", "portable-net45+win8"]
  5. }
  6. },

Build Options: Options, which are passed to the compiler while building the Application.

  1. "buildOptions": {
  2. "emitEntryPoint": true,
  3. "preserveCompilationContext": true
  4. },

RuntimeOptions: Manage Server garbage collection at Application runtime.

  1. "runtimeOptions": {
  2. "configProperties": {
  3. "System.GC.Server": true
  4. }
  5. },

PublishOptions: This defines the file/folder to include/exclude to/from the output folder, while publishing the Application.

  1. "publishOptions": {
  2. "include": ["wwwroot", "web.config"]
  3. },

Scripts: Scripts is an object type, which specifies that scripts run during building or publishing the Application.

  1. "scripts": {
  2. "postpublish": ["dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%"]
  3. }

Add MVC6
It’s time to add MVC6. In .NET Core 1.0 MVC & Web API are unified, and become a single class, which inherits from the same base class.
Let’s add MVC Service to our Application. Open project.json to add new dependencies in it. In dependencies section, add two dependencies.

  • "Microsoft.AspNetCore.Mvc": "1.0.0",
  • "Microsoft.AspNetCore.StaticFiles": "1.0.0"

Click Save.

It will start restoring the packages automatically.

Now let’s add MVC (midleware) to request pipeline in Config method at startup class.

  1. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {
  2. loggerFactory.AddConsole();
  3. if (env.IsDevelopment()) {
  4. app.UseDeveloperExceptionPage();
  5. }
  6. //app.UseStaticFiles();
  7. app.UseMvc(routes => {
  8. routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");
  9. });
  10. }

In ConfigureServices method, we need to add framework Service. We have added services.AddMvc();

  1. public void ConfigureServices(IServiceCollection services) {
  2. services.AddMvc();
  3. }

MVC Folder Structure
Let’s add MVC folder structure to our sample Application. We have added view files in the views folder & MVC controller in Controllers folder like old MVC Application.

Here, you may notice that there is a new file in the views folder “_ViewImports.cshtml”. This file is responsible for setting up the namespaces, which can be accessed by the views in the project, which was previously done by the Web.config file in the views folder.
We are almost done. Let’s modify our view content with welcome message. Now, run the Application. You can see welcome message appears in the home page.

Output
AngularJS2
AngularJS2 is a modern Client end JavaScript Framework for the Application development. This JavaScript framework is totally new & written, based on TypeScript.
We will follow the steps, given below, to learn, how we install it to our Application,

  1. Manage Client-side Dependencies
  2. Use Package Manager (NPM).
  3. Use Task Runner.
  4. Bootstrapping using Type Script.

Client-side Dependencies: We need to add a JSON config file for Node Package Manager(NPM). Click add > New Item > Client- Side > npm Configuration File and click OK.

Open our newly added npm config file and modify the initial settings.
Package.json

  1. {
  2. "version": "1.0.0",
  3. "name": "asp.net",
  4. "private": true,
  5. "Dependencies": {
  6. "angular2": "2.0.0-beta.9",
  7. "systemjs": "0.19.24",
  8. "es6-shim": "^0.33.3",
  9. "rxjs": "5.0.0-beta.2"
  10. },
  11. "devDependencies": {
  12. "gulp": "3.8.11",
  13. "gulp-concat": "2.5.2",
  14. "gulp-cssmin": "0.1.7",
  15. "gulp-uglify": "1.2.0",
  16. "rimraf": "2.2.8"
  17. }
  18. }

In the dependencies section, we need to add AngularJS2 with other dependencies and they are for:

  1. Es6-shim is a library, which provides compatibility on old environment.
  2. Rxjs provides more modular file structure in a variety of formats.
  3. SystemJS enables System.import TypeScript files directly.

As you can see, there are two different type objects; one is dependencies, which are used for the production purposes & the other one is devDependencies for development related things, like gulp is to run different tasks.
Click save. It will restore automatically. Here, we have all our required packages in the Dependencies section.

In this application we have added another package manager called Bower, Click add > New Item > Client- Side > Bower Configuration File then click Ok.

Comparing with NPM,
 
Bower:
  1. Manage html, css, js component
  2. Load minimal resources
  3. Load with flat dependencies
NPM:
 
  1. Install dependencies recursively
  2. Load nested dependencies
  3. Manage NodeJS module
Open the config file then add required dependencies in dependencies secction with specific version.
 
Save the JSON file after edit, it will automatically restore that package in our project. Here you can see we have added Jquery & Bootstrap package with Bower package manager.
 
 
 
Now, let’s add a gulp configuration file to run the task. Click Add > New Item > Client-Side. Select gulp JSON file to include.

Gulp.json
  1. /*
  2. This file in the main entry point for defining Gulp tasks and using Gulp plugins.
  3. Click here to learn more. http://go.microsoft.com/fwlink/?LinkId=518007
  4. */
  5. "use strict";
  6. var gulp = require("gulp");
  7. var root_path = {
  8. webroot: "./wwwroot/"
  9. };
  10. //library source
  11. root_path.nmSrc = "./node_modules/";
  12. //library destination
  13. root_path.package_lib = root_path.webroot + "lib-npm/";
  14. gulp.task("copy-systemjs", function() {
  15. return gulp.src(root_path.nmSrc + '/systemjs/dist/**/*.*', {
  16. base: root_path.nmSrc + '/systemjs/dist/'
  17. }).pipe(gulp.dest(root_path.package_lib + '/systemjs/'));
  18. });
  19. gulp.task("copy-angular2", function() {
  20. return gulp.src(root_path.nmSrc + '/angular2/bundles/**/*.js', {
  21. base: root_path.nmSrc + '/angular2/bundles/'
  22. }).pipe(gulp.dest(root_path.package_lib + '/angular2/'));
  23. });
  24. gulp.task("copy-es6-shim", function() {
  25. return gulp.src(root_path.nmSrc + '/es6-shim/es6-sh*', {
  26. base: root_path.nmSrc + '/es6-shim/'
  27. }).pipe(gulp.dest(root_path.package_lib + '/es6-shim/'));
  28. });
  29. gulp.task("copy-rxjs", function() {
  30. return gulp.src(root_path.nmSrc + '/rxjs/bundles/*.*', {
  31. base: root_path.nmSrc + '/rxjs/bundles/'
  32. }).pipe(gulp.dest(root_path.package_lib + '/rxjs/'));
  33. });
  34. gulp.task("copy-all", ["copy-rxjs", 'copy-angular2', 'copy-systemjs', 'copy-es6-shim']);

To run the task, right click on Gulp.json file to reload.

Right click on copy-all & click run.

Task run & finish.

In Solution Explorer, all the required packages are copied. We also need to put the type definitions for es6-shim(typing folder), without this, it will cause error - "Cannot find name 'Promise'".
 

Bootstrapping with TypeScript
tsConfig.json

  1. {
  2. "compilerOptions": {
  3. "noImplicitAny": false,
  4. "noEmitOnError": true,
  5. "removeComments": false,
  6. "sourceMap": true,
  7. "target": "es5",
  8. //add this to compile app component
  9. "emitDecoratorMetadata": true,
  10. "experimentalDecorators": true,
  11. "module": "system",
  12. "moduleResolution": "node"
  13. },
  14. "exclude": ["node_modules", "wwwroot/lib"]
  15. }

noImplicitAny : Raise an error on the expressions and declarations with an implied ‘any’ type. noEmitOnError: Do not emit outputs, if any errors were reported. Target : Specify ECMAScript target version: ‘es5’ (default), ‘es5’, or ‘es6’. experimentalDecorators : Enables an experimental support for ES7 decorators.
Get more details on Compiler option here.
Create an app folder for .ts file in wwwroot folder.

In Solution Explorer, you may add the files, given below.

In main.ts code snippet, bootstrap AngularJS with importing the component.

  1. import {bootstrap} from 'angular2/platform/browser';
  2. import {AppComponent} from './app.component';
  3. import {enableProdMode} from 'angular2/core';
  4. enableProdMode();
  5. bootstrap(AppComponent);

Component: imports the Component function from Angular 2 library; use of import, app component class can be imported from other component. import {Component} from 'angular2/core';

  1. @Component({
  2. selector: 'core-app',
  3. template: '<h3>Welcome to .NET Core 1.0 + MVC6 + Angular 2</h3>'
  4. })
  5. export class AppComponent {}

MVC View: It’s time to update our layout & linkup the library.

Now, we will add the reference to our layout page.

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta name="viewport" content="width=device-width" />
  5. <title>@ViewBag.Title</title>
  6. <script src="~/lib-npm/es6-shim/es6-shim.js"></script>
  7. <script src="~/lib-npm/angular2/angular2-polyfills.js"></script>
  8. <script src="~/lib-npm/systemjs/system.src.js"></script>
  9. <script src="~/lib-npm/rxjs/Rx.js"></script>
  10. <script src="~/lib-npm/angular2/angular2.js"></script>
  11. </head>
  12. <body>
  13. <div> @RenderBody() </div> @RenderSection("scripts", required: false) </body>
  14. </html> Index.cshtml @{ ViewData["Title"] = "Home Page"; }
  15. <core-app>
  16. <div>
  17. <p><img src="~/img/ajax_small.gif" /> Please wait ...</p>
  18. </div>
  19. </core-app> @section Scripts {
  20. <script>
  21. System.config({
  22. packages: {
  23. 'app': {
  24. defaultExtension: 'js'
  25. }
  26. },
  27. });
  28. System.import('app/main').then(null, console.error.bind(console));
  29. </script> }

One more thing to do is to enable the static file serving. Add this line to startup config method.
app.UseStaticFiles();
Build & run application
Finally, build & run the Application.

Output
Here, we can see our app is working with AngularJS2.

 

[转]Using MVC 6 And AngularJS 2 With .NET Core的更多相关文章

  1. 如何在 ASP.NET MVC 中集成 AngularJS(3)

    今天来为大家介绍如何在 ASP.NET MVC 中集成 AngularJS 的最后一部分内容. 调试路由表 - HTML 缓存清除 就在我以为示例应用程序完成之后,我意识到,我必须提供两个版本的路由表 ...

  2. 如何在 ASP.NET MVC 中集成 AngularJS(2)

    在如何在 ASP.NET MVC 中集成 AngularJS(1)中,我们介绍了 ASP.NET MVC 捆绑和压缩.应用程序版本自动刷新和工程构建等内容. 下面介绍如何在 ASP.NET MVC 中 ...

  3. 前端MVC学习总结——AngularJS验证、过滤器

    前端MVC学习总结--AngularJS验证.过滤器 目录 一.验证 二.过滤器 2.1.内置过滤器 2.1.1.在模板中使用过滤器 2.1.2.在脚本中调用过滤函数 2.2.自定义过滤器 三.指令( ...

  4. 如何在 ASP.NET MVC 中集成 AngularJS(1)

    介绍 当涉及到计算机软件的开发时,我想运用所有的最新技术.例如,前端使用最新的 JavaScript 技术,服务器端使用最新的基于 REST 的 Web API 服务.另外,还有最新的数据库技术.最新 ...

  5. [angularjs] MVC + Web API + AngularJs 搭建简单的 CURD 框架

    MVC + Web API + AngularJs 搭建简单的 CURD 框架 GitHub 地址:https://github.com/liqingwen2015/Wen.MvcSinglePage ...

  6. ASP.NET MVC下使用AngularJs语言(六):获取下拉列表的value和Text

    前面Insus.NET有在Angularjs实现DropDownList的下拉列表的功能.但是没有实现怎样获取下拉列表的value和text功能. 下面分别使用ng-click和ng-change来实 ...

  7. ASP.NET MVC下使用AngularJs语言(五):ng-selected

    这次学习ng-selected语法,这个是为DropDownList下拉列表显示默认选项. 演示从下面步骤开始 1,新建一个model: 上面#14行代码的property,数据类型为bool.即是存 ...

  8. ASP.NET MVC下使用AngularJs语言(二):ng-click事件

    程序用户交互,用户使用mouse点击,这是一个普通的功能. 在angularjs的铵钮点击命令是ng-click. 创建Angularjs的app使用前一篇<ASP.NET MVC下使用Angu ...

  9. ASP.NET MVC下使用AngularJs语言(一):Hello your name

    新春节后,分享第一个教程. 是教一位新朋友全新学习ASP.NET MVC下使用AngularJs语言. 一,新建一个空的Web项目.使用NuGet下载AngularJs和jQuery.二,配置Bund ...

随机推荐

  1. SDOI2010粟粟的书架

    题目传送:https://www.luogu.org/problemnew/show/P2468 这是一个二合一的题目,前50% \(n!=1\)的分数中,我们考虑用动态规划来做. 设\(sum[i] ...

  2. “全栈2019”Java第四十三章:封装

    难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java第 ...

  3. bzoj4199: [Noi2015]品酒大会(后缀数组)

    题目描述 一年一度的“幻影阁夏日品酒大会”隆重开幕了.大会包含品尝和趣味挑战 两个环节,分别向优胜者颁发“首席品酒家”和“首席猎手”两个奖项,吸引了众多品酒师参加. 在大会的晚餐上,调酒师 Rainb ...

  4. linux下的常用指令

    1,在vim中查找字符段 :1?字段名,此方式可以从开始向下查询字段了. :?字段名 ,查询字都段: 2,修改某个文件夹用户和组 修改文件所属用户:chown [-R] 用户 文件或目录 如:chow ...

  5. 数论 CF230B T-primes

    CF230B T-primes 我们知道质数是只有两个不同的正数因数的正整数.相似的,我们把一个正整数 t 叫做 T质数,如果 t 恰好有三个不同的正整数因数. 你被给了一个含有 n 个正整数的数组. ...

  6. python cookbook

    一 .数据结构 python collections包中 deque :固定长度队列,(例如固定长度的cache什么的) defaultdict:如果每个键值不存在,默认返回值 orderdict:有 ...

  7. Linx 的组管理和权限管理

    Linux组基本介绍 在linux中的每个用户必须属于一个组,不能独立于组外.在linux中每个文件 有所有者.所在组.其它组的概念. 1) 所有者 2) 所在组 3) 其它组 4) 改变用户所在的组 ...

  8. [Alpha]Scrum Meeting#6

    github 本次会议项目由PM召开,时间为4月8日晚上10点30分 时长25分钟 任务表格 人员 昨日工作 下一步工作 木鬼 整理开会记录 撰写并发布之前因为清明耽误的博客 SiMrua 寻找方法捕 ...

  9. 高阶篇:4.3)FTA故障树分析法-DFMEA的另外一张脸

    本章目的:明确什么是FTA,及与DFMEA的关系. 1.FTA定义 故障树分析(FTA) 其一:故障树分析(Fault Tree Analysis,简称FTA)又称事故树分析,是安全系统工程中最重要的 ...

  10. readonly与disable

    Readonly只针对input(text / password)和textarea有效,而disabled对于所有的表单元素都有效,但是表单元素在使用了disabled后,当我们将表单以POST或G ...