Microsoft > Other >> Programming Views : 47531
Angular With MVC
Rate This Article :

Integrate Angular with ASP.NET MVC

Introduction:

This article will showcase the basic set up of angular integrated with ASP.Net MVC.

Pre-requisites:

Install visual studio 2015(Even u can use 2013). Click here to download

Install Node js package for visual studio. Click here to download

Install Typescript package for visual studio. Click here to download

Reader should have basic knowledge on MVC architecture and Angular 2 for better understanding.

Create a sample MVC application with angular:

Step 1: Add New MVC Project 

· Create new project with the below steps.

              deploy1.png


deploy2.png


deploy3.png


Step 2: Add a package file for angular

      ·         Add a package.json file to import required references with below steps.

      ·         Right click on project, Add à New item

deploy4.png

        ·         Search with package.json and Add.

deploy5.png

       ·         Paste the below code snippet in the created package.json file.


{

  "name": "angular-quickstart",

  "version": "1.0.0",

  "description": "QuickStart package.json from the documentation, supplemented with testing support",

  "scripts": {

    "build": "tsc -p src/",

    "build:watch": "tsc -p src/ -w",

    "build:e2e": "tsc -p e2e/",

    "serve": "lite-server -c=bs-config.json",

    "serve:e2e": "lite-server -c=bs-config.e2e.json",

    "prestart": "npm run build",

    "start": "concurrently \"npm run build:watch\" \"npm run serve\"",

    "pree2e": "npm run build:e2e",

    "e2e": "concurrently \"npm run serve:e2e\" \"npm run protractor\" --kill-others --success first",

    "preprotractor": "webdriver-manager update",

    "protractor": "protractor protractor.config.js",

    "pretest": "npm run build",

    "test": "concurrently \"npm run build:watch\" \"karma start karma.conf.js\"",

    "pretest:once": "npm run build",

    "test:once": "karma start karma.conf.js --single-run",

    "lint": "tslint ./src/**/*.ts -t verbose"

  },

  "keywords": [],

  "author": "",

  "license": "MIT",

  "dependencies": {

    "@angular/common": "~4.3.4",

    "@angular/compiler": "~4.3.4",

    "@angular/core": "~4.3.4",

    "@angular/forms": "~4.3.4",

    "@angular/http": "~4.3.4",

    "@angular/platform-browser": "~4.3.4",

    "@angular/platform-browser-dynamic": "~4.3.4",

    "@angular/router": "~4.3.4",

    "angular-in-memory-web-api": "~0.3.0",

    "systemjs": "0.19.40",

    "core-js": "^2.4.1",

    "rxjs": "5.0.1",

    "zone.js": "^0.8.4"

  },

  "devDependencies": {

    "concurrently": "^3.2.0",

    "lite-server": "^2.2.2",

    "typescript": "~2.1.0",

    "canonical-path": "0.0.2",

    "tslint": "^3.15.1",

    "lodash": "^4.16.4",

    "jasmine-core": "~2.4.1",

    "karma": "^1.3.0",

    "karma-chrome-launcher": "^2.0.0",

    "karma-cli": "^1.0.1",

    "karma-jasmine": "^1.0.2",

    "karma-jasmine-html-reporter": "^0.2.2",

    "protractor": "~4.0.14",

    "rimraf": "^2.5.4",

    "@types/node": "^6.0.46",

    "@types/jasmine": "2.5.36"

  },

  "repository": {}

}


      ·         After added the code, right click on file and choose “Restore Package” option,

deploy6.png

      ·         After updated you will see the folder “node_modules” in the project

deploy7.png


Step 3: Add system configuration java script file.

      ·         Add systemjs.config.js file to specify the reference path to the components 

       ·         Right click on project, Add à JavaScript File

deploy8.png

      ·         Give name as “systemjs.config.js” and click OK.

deploy9.png

      ·       Paste the below code snippet in the created systemjs.config.js file.


System.config({

    paths: {

      // paths serve as alias

      'npm:': 'node_modules/'

    },

    // map tells the System loader where to look for things

    map: {

      // our app is within the app folder

      'app': 'app',

      // angular bundles

      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',

      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',

      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',

      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',

      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',

      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',

      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',

      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',

      // other libraries

      'rxjs':                      'npm:rxjs',

      'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js'

    },

    // packages tells the System loader how to load when no filename and/or no extension

    packages: {

      app: {

        defaultExtension: 'js',

        meta: {

          './*.js': {

            loader: 'systemjs-angular-loader.js'

          }

        }

      },

      rxjs: {

        defaultExtension: 'js'

      }

    }

  });


Step 4: Add typescript configuration file.

      ·         Add tsconfig.json file to specify the compiler options for building  

deploy11.png

      ·      Choose Typescript JSON Configuration file and Paste the below code snippet in the created tsconfig.json file.


deploy12.png

deploy11.png



  "compilerOptions": { 
    "target": "es5", 
    "module": "commonjs", 
    "moduleResolution": "node", 
    "sourceMap": true, 
    "emitDecoratorMetadata": true, 
    "experimentalDecorators": true, 
    "lib": [ "es2015", "dom" ], 
    "noImplicitAny": true, 
    "suppressImplicitAnyIndexErrors": true 
  } 
}

Step 5: Route the URL for accepting angular

     ·         Open “RouteConfig.cs” file and add the below code to allow URL which accept angular input,

routes.MapRoute(

                name: "angular",

                url: "{*anything}",

                defaults: new { controller = "Home", action = "Index" } // The view that bootstraps Angular 2

            );


Step 6: Add Angular Reference

·         Add angular reference by including below snippet in the layout file.

    <script src="/node_modules/zone.js/dist/zone.js"></script>

    <script src="/node_modules/systemjs/dist/system.src.js"></script>

    <script src="/systemjs.config.js"></script>

    <script>

   System.import('app').catch(function(err){ console.error(err); });

    </script>

·         Add folder namely “app”,

deploy12.png


Step 7: Setup Angular structure

·         Create angular app module file “app.module.ts”

deploy13.png

deploy14.png

·         Paste the below code snippet in the app module,

import { NgModule } from '@angular/core';

import { APP_BASE_HREF } from '@angular/common';

import { BrowserModule } from '@angular/platform-browser';

import { ReactiveFormsModule } from '@angular/forms';

import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';

import { routing } from './app.routing';

import { HomeComponent } from './Component/home.component';

import { AboutComponent } from './Component/about.component';

@NgModule({

    imports: [BrowserModule, ReactiveFormsModule, HttpModule, routing],

    declarations: [AppComponent, HomeComponent, AboutComponent],

    providers: [{ provide: APP_BASE_HREF, useValue: '/' }],

    bootstrap: [AppComponent]

})

export class AppModule { }

·         Create angular main file “main.ts”

deploy15.png

deploy16.png

·       Paste the below code snippet in below file,

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app.module';

platformBrowserDynamic().bootstrapModule(AppModule);

·         Create app component file “app.component.ts” and paste the below code snippet,

import { Component } from "@angular/core"

@Component({

    selector: "user-app",

    template: `

               <div>

                  <nav class='navbar navbar-inverse'>

                       <div class='container-fluid'>

                         <ul class='nav navbar-nav'>

                           <li><a [routerLink]="['home']">Home</a></li>

                           <li><a [routerLink]="['about']">About</a></li>

                      </ul>

                      </div>

                 </nav>   

              <div class='container'>

                <router-outlet></router-outlet>

              </div>

             </div>         

`

})

export class AppComponent {

}

·         Create app component file “app.routing.ts” and update the routing for created modules.

·         Create Home and About Component

·         Create app component file “home.component.ts” and paste the below code snippet,

import { Component } from "@angular/core";

@Component({

    template: `<p>This is home page.</p>`

})

export class HomeComponent {

}

·         Create app component file “about.component.ts” and paste the below code snippet,

import { Component } from "@angular/core";

@Component({

    template: `<p>This is about page.</p>`

})

export class AboutComponent {

}

Step 8: Adding code reference in index.cshtml file.

·         Remove existing code and paste the below code snippet in index.cshtml file

@{

    ViewBag.Title = "Index";

}

<body>

    <user-app> This is normal ASP.Net MVC</user-app>

</body>

Step 9: Build and run application

·         Load Angular Output by entering url “http://localhost:portnumber/home

deploy17.png

·         Click on about link to see the navigation,

deploy18.png

·        Load MVC Output by entering url “http://localhost:portnumber/home/index 


deploy19.png

  

About Author
Karthik G
Total Posts 3
-
Comment this article
Name*
Email Address* (Will not be shown on this website.)
Comments*
Enter Image Text*
   
View All Comments
Pratik Jain
System.import('app').catch(function (err) { console.error(err); }); Creating issue in my project _Layout.cshtml Getting error ervertime running the projectGET https://localhost:port/app/ 403 error
nidhi
Hi! thanks .
Rajkumar
Yes Kumar. You can implement in another way. Keep a separate project for angular, publish the code and deploy it along with MVC code by creating a separate folder.
Kumar
Thanks for you great explanation. Can we implement both angular and mvc in same project. some pages in mvc with cshtml and some pages in angular. Example I have login form in mvc view and after login redirect to dashboard(dashboard in angular)
salmon chowdary
Good Content, please share a link over curd operations with angular 6 + MVC 5
Karthik
Thanks Siva. Please let me know if you have doubts while implementing the same in your project.
Karthik
Thanks for the highlighting this, Jayanthan. Added appropriate code snippet in step 4.
Jayanthan
Thanks for the Article. In Step 4: Add typescript configuration file. Choose Typescript JSON Configuration file and Paste the below code snippet in the created tsconfig.json file. There is no code present for copy paste. Please update the same. Thanks, Jayanthan
siva
Very useful article. It helped me to understand from the scratch. i will try to implement in my project.
  Privacy   Terms Of Use   Contact Us
© 2016 Developerin.Net. All rights reserved.
Trademarks and Article Images mentioned in this site may belongs to Microsoft and other respective trademark owners.
Articles, Tutorials and all other content offered here is for educational purpose only and its author copyrights.