ASP.NET Core 1.0 MVC 6 Using WEB API And AngularJS

aspnet

Introduction

In this article we will see in detail how to create ASP.NET Core 1.0 MVC 6 using WEB API and AngularJS .

You can also view our previous article.

Prerequisites

Visual Studio 2015: You can download it from here.
ASP.NET 5 /Core 1.0: download ASP.NET 5 RC from this link.

In this article we will see in detail how to:

  • Create our ASP.NET Core 1.0 Web Application.
  • How to change the Default Connection string to our SQL Server Connection String.
  • How to add Model and DbContext Class for using in WEB API
  • How to add Entity framework Service in Startup.cs file.
  • How to add our WEB API Controller.
  • How to add grunt package using NPM configuration file
  • How to configure Grunt File.
  • How to Run the Grunt file using Visual Studio Task Runner Explorer
  • How to create our AngularJS Module, Controller and Service file and get WEB API data for bind in MVC page.

Reference link  

Using the code

Create a Database

We will be using our SQL Server database for our WEB API. First we create a database named  StudentsDB and a table as StudentMaster. Here is the SQL script to create Database table and sample record insert query in our table.
  1. USEMASTER  
  2. GO  
  3.   
  4. -- 1) Check for the Database Exists .If the database is exist then drop and create new DB   
  5. IFEXISTS(SELECT [name] FROMsys.databasesWHERE [name] ='StudentsDB')  
  6. DROPDATABASEStudentsDB  
  7. GO  
  8.   
  9. CREATEDATABASEStudentsDB  
  10. GO  
  11.   
  12. USEStudentsDB  
  13. GO  
  14.   
  15.   
  16. -- 1) //////////// StudentMasters  
  17.   
  18. IFEXISTS(SELECT [name] FROMsys.tablesWHERE [name] ='StudentMasters')  
  19. DROPTABLEStudentMasters  
  20. GO  
  21.   
  22. CREATETABLE [dbo].[StudentMasters](  
  23. [StdID] INTIDENTITYPRIMARYKEY,  
  24. [StdName] [varchar](100)NOTNULL,  
  25. [Email] [varchar](100)NOTNULL,  
  26. [Phone] [varchar](20)NOTNULL,  
  27. [Address] [varchar](200)NOTNULL  
  28. )  
  29.   
  30. -- insert sample data to Student Master table  
  31. INSERTINTO [StudentMasters]([StdName],[Email],[Phone],[Address])  
  32. VALUES ('Shanu','[email protected]','01030550007','Madurai,India')  
  33.   
  34. INSERTINTO [StudentMasters]([StdName],[Email],[Phone],[Address])  
  35. VALUES ('Afraz','[email protected]','01030550006','Madurai,India')  
  36.   
  37. INSERTINTO [StudentMasters]([StdName],[Email],[Phone],[Address])  
  38. VALUES ('Afreen','[email protected]','01030550005','Madurai,India')  
  39.   
  40.   
  41. select*from [StudentMasters]  
Create our ASP.NET Core 1.0 Web Application.

After installing both Visual Studio 2015 and ASP.NET 5 RC.click Start, then Programs and select Visual Studio 2015 - Click Visual Studio 2015. Click New, then Project, select Web and select ASP.NET Web Application. Enter your Project Name and click OK.

new

Select Web Application under ASP.NET 5 Template and click ok.

template

Database Connection String:

Now we need to change the local connection string from ASP.Net 5 project with our SQL Server connection.

Note:

In ASP.NET 5 we need to use “appsettings.json” file instead of web.config. Yes in ASP.NET 5 there is no web.Config file for connection string we need use the “appsettings.json” .We can find the “appsettings.json” file from our Asp.NET 5 solution.

test

To change the default connection string with our SQL connection open the “appsettings.json” file .Yes this is a JSON file and this file looks like the below Image by default.

code

Now the default connectionstring will be something like this,
  1. "ConnectionString""Server=(localdb)\\mssqllocaldb;Database=aspnet5-MYASP.NET5DemoTest-afb3aac0-d181-4278-8436-cafeeb5a8dbf;Trusted_Connection=True;MultipleActiveResultSets=true"  
Now we change this to our SQL Connection like below,
  1. "ConnectionString""Server=YourSQLSERVERNAME;Database=StudentsDB;user id=SQLID;password=SQLPWD;Trusted_Connection=True;MultipleActiveResultSets=true;"  
Here you can change as per your SQL Connection and save the “appsettings.json” file. The updated JSON file will be looks like this.

code

Creating our Model

We can create a model by adding a new class file in our Model Folder.

test

Right click the Models folder and click add new Item .Select Class and enter your class name as “StudentMasters.cs”

add

Here our class will be look like the below image. Here we will add our model field property.

model

Add the header file usingSystem.ComponentModel.DataAnnotations; and add all our table field name as property in this model class like the below code.

  1. using System;  
  2. usingSystem.Collections.Generic;  
  3. usingSystem.Linq;  
  4. usingSystem.Threading.Tasks;  
  5. usingSystem.ComponentModel.DataAnnotations;  
  6.   
  7. namespace MYASP.NET5DemoTest.Models  
  8. {  
  9.     publicclassStudentMasters  
  10.     {  
  11.         [Key]  
  12.         publicintStdID  
  13.         {  
  14.             get;  
  15.             set;  
  16.         }  
  17.         [Required]  
  18.         [Display(Name = "Name")]  
  19.         publicstringStdName  
  20.         {  
  21.             get;  
  22.             set;  
  23.         }  
  24.         [Required]  
  25.         [Display(Name = "Email")]  
  26.         publicstring Email   
  27.         {  
  28.             get;  
  29.             set;  
  30.         }  
  31.   
  32.         [Required]  
  33.         [Display(Name = "Phone")]  
  34.         publicstring Phone  
  35.         {  
  36.             get;  
  37.             set;  
  38.         }  
  39.   
  40.   
  41.         publicstring Address  
  42.         {  
  43.             get;  
  44.             set;  
  45.         }  
  46.     }  
  47. }  
Now we have created our Model, thenext step is to add DBContext for our model.

Creating DbContext

Now we need to create a DBContext for our Entity Framework. Same as with Model Class, add a new class to our Models folder.

Right click the Models folder and click add new Item .Select Class and enter your class name as “StudentMastersAppContext.cs”

add

Here our class will be look like the below image.

code

Now first we need to add the header file for Entity framework as usingMicrosoft.Data.Entity;

Next inherit the DbContextto our class and then create object for our DBContext like below code.
  1. usingSystem.Collections.Generic;  
  2. usingSystem.Linq;  
  3. usingSystem.Threading.Tasks;  
  4. usingMicrosoft.Data.Entity;  
  5.   
  6. namespace MYASP.NET5DemoTest.Models  
  7. {  
  8.     publicclassStudentMastersAppContext: DbContext  
  9.     {  
  10.         publicDbSet < StudentMasters > Students  
  11.         {  
  12.             get;  
  13.             set;  
  14.         }  
  15.     }  
  16. }  

Now we can created our DB context and the next step is to add a Service for our Entity Framework.

Adding Entity Framework Service in Startup.cs

Next we need to add our Entity Framework service in Startup.cs . We can find the Startup.cs file from our solution explorer .

test

Open the Startup.csfile and we can see by default the ApplicationDBContext will be added in ConfigureServices method.

code

Now we can add one more DBContext for our StudentMastersAppContext like below code.
  1. // Add Entity Framework  
  2. services.AddEntityFramework()  
  3.     .AddSqlServer()  
  4.     .AddDbContext < StudentMastersAppContext > (options =>  
  5.         options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));  
  6.   
  7. In ConfigureServices method we add like this code below.  
  8.   
  9. publicvoidConfigureServices(IServiceCollection services)  
  10. {  
  11.     // Add framework services.  
  12.     services.AddEntityFramework()  
  13.         .AddSqlServer()  
  14.         .AddDbContext < ApplicationDbContext > (options =>  
  15.             options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));  
  16.   
  17.     services.AddIdentity < ApplicationUser, IdentityRole > ()  
  18.         .AddEntityFrameworkStores < ApplicationDbContext > ()  
  19.         .AddDefaultTokenProviders();  
  20.   
  21.     services.AddMvc();  
  22.   
  23.     // Add Entity Framework  
  24.     services.AddEntityFramework()  
  25.         .AddSqlServer()  
  26.         .AddDbContext < StudentMastersAppContext > (options =>  
  27.             options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));  
  28.   
  29.     // Add application services.  
  30.     services.AddTransient < IEmailSender, AuthMessageSender > ();  
  31.     services.AddTransient < ISmsSender, AuthMessageSender > ();  
  32. }  
Next step is to add WEBAPI Controller.

Creating our WEB API Controller

Right click the Controller folder and click add new Item .Select API Controller with Action, using Entity Framework and click Add.

scaffold

Now we need to select our newly created Model class and our Data Context Class.

Model Class: In Model Class select our Model Class which we created as “StudentMasters”.

Data Context Class: In Data Context select our DBContext class which we created as “StudentMastersAppContext”

controller

Give our Controller name with API and click ADD.

Now we can see our WEB API Controller has been created,

code

To test it we can run our project and copy the get method api path here we can see our API path for get is api/StudentMasters/

Run the program and paste the above API path to test our output.

output

Create Scripts and Controller Folder:

Next we need to add a new folder in our project for AngularJs.
Create a new folder named “Scripts” .Right click our project and click add new Folder and name the folder as “Scripts”

test

Now we create one more folder for our AngularJs controller named as “Controllers”

test

Adding grunt package using NPM configuration file

Now we need to add a NPM Configuration File for adding a grunt package to run our Java scripts.
As we have created as a Web Application the NPM Configuration File will be located in our project.
By default we can’t view our NPM Configuration File. The NPM Configuration File will be in the name of “package.JSON”. TO view that from the Solution Explorer click on “Show All Files”

test

Now we can see NPM file as “package.JSON”

json

Dependencies Folder:

folder

In dependency folder we can see the entire installed NPM package. Here we can see by default grunt package has not been installed .Here we will see how to add the grunt package.

If this “package.JSON” is not available

Right click our Project and click Add New Item to add our NPM Configuration File. Select Client-Side and Select NPM Configuration File and click Add.

add

Now open the “package.JSON” file .Now first we need to change the name to our project Solution name and add our grunt package. We can see the code here below the image.

code

Here we have changed the name as our Solution name and also added the grunt package.
  1. {  
  2.     "name""testforDemo",  
  3.     "version""0.0.0",  
  4.     "devDependencies":   
  5.     {  
  6.         "gulp""3.8.11",  
  7.         "gulp-concat""2.5.2",  
  8.         "gulp-cssmin""0.1.7",  
  9.         "gulp-uglify""1.2.0",  
  10.         "rimraf""2.2.8",  
  11.         "grunt""0.4.5",  
  12.         "grunt-contrib-uglify""0.9.1",  
  13.         "grunt-contrib-watch""0.6.1"  
  14.     }  
  15. }  

After adding the grunt file save the file .Now we can see in the Dependencies folder, Now save the package.json file and you should be able to see a grunt package under Dependencies/ npm Folder.

npm

Once we click on save “package.json: the “Dependencies” and “npm” folder will be as “Restoring”.

restore

Now right click the “Dependencies” folder and click Restore Packages. This will install all the packages to your npm folder.

dependencies

Configure Grunt File.

Grunt is used to build all our client side resources like JavaScript for our project.

First step is to we need to add a Grunt file to our project. Right click our project and Select Client-Side and Select Grunt Configuration File and click Add.

add

Here we can see now we have added the Grunt file to our project. Next we need to edit this file to add loadplugins, configure plugins and define tasks,

code

Here in our Grunt file we have first loaded plugins which we have added in our npm. Using loadNpmTask here we load 'grunt-contrib-uglify' ,'grunt-contrib-watch'

npm

Next we configure the grunt, add the app.js file in our wwwrootfolder. All our Script files from Scripts folder result will be added in this app.js file.

The watch plugin will be used to check for any changes on JavaScript file and update it app.js with all new changes.
  1. /* 
  2. This file in the main entry point for defining grunt tasks and using grunt plugins. 
  3. Click here to learn more. http://go.microsoft.com/fwlink/?LinkID=513275&clcid=0x409 
  4. */  
  5. module.exports = function(grunt)  
  6. {  
  7.     grunt.loadNpmTasks('grunt-contrib-uglify');  
  8.     grunt.loadNpmTasks('grunt-contrib-watch');  
  9.   
  10.     grunt.initConfig  
  11.     ({  
  12.         uglify:   
  13.       {  
  14.             my_target:  
  15.           {  
  16.                 files:  
  17.                 {  
  18.                     'wwwroot/app.js': ['Scripts/app.js''Scripts/**/*.js']  
  19.                 }  
  20.             }  
  21.         },  
  22.   
  23.         watch:  
  24.       {  
  25.             scripts:  
  26.             {  
  27.                 files: ['Scripts/**/*.js'],  
  28.                 tasks: ['uglify']  
  29.             }  
  30.         }  
  31.     });  
  32.   
  33.     grunt.registerTask('default', ['uglify''watch']);  
  34. };  
Save the file.

Run the Grunt file using Visual Studio Task Runner Explorer

Now we need to run the Grunt file using Visual Studio Task Runner.

To view the Task RunnerClick the menu View-> Other Windows,-> and click on Task Runner Explorer.

task

Now we can see our Task Runner Explorer.

explorer

Click on GruntFile.js and click on refresh button at top left.

grunt

Now we can see all the GruntFile has been added.

file

Right click the default under Alias Task and click Run.

run

Now our Grunt file has been successfully run in our project. When we add a script file we can see new app.js file will be created in our wwwroot folder.

folder

Create our AngularJS Module, Controller and Service

Creating AngularJS  Module:

Now we will create a new AngularJs module under our Scripts folder.

Right click our Scripts folder and click add new Item and Select Client-Side and Select AngularJs Module and click Add.

add

Now we can see a default AngularJS Module code like below.

  1. (function()   
  2.  {  
  3.     'use strict';  
  4.   
  5.     angular.module('app', [  
  6.         // Angular modules   
  7.         'ngRoute'  
  8.   
  9.         // Custom modules   
  10.   
  11.         // 3rd Party Modules  
  12.   
  13.     ]);  
  14. })();  
Change this with our Module Name and service name for calling WEB API and binding from Controller.
  1. (function()  
  2.  {  
  3.     'use strict';  
  4.   
  5.     angular.module('studentapp', [  
  6.         // Angular modules   
  7.         'studentService'  
  8.   
  9.         // Custom modules   
  10.   
  11.         // 3rd Party Modules  
  12.   
  13.     ]);  
  14. })();  
Creating AngularJS Service:

Now we will create a new AngularJsServiceunder Controllers folder inside Scripts folder.

Right click our Controllers folder under Scripts folder and clicks add new Item ,Select Client-Side and Select AngularJsFactory and click Add.

add

Now we can see the default code will be look like this below.
  1. (function()  
  2.  {  
  3.     'use strict';  
  4.   
  5.     angular  
  6.         .module('app')  
  7.         .factory('factory', factory);  
  8.   
  9.     factory.$inject = ['$http'];  
  10.   
  11.     function factory($http)  
  12.     {  
  13.         var service =   
  14.         {  
  15.             getData: getData  
  16.         };  
  17.   
  18.         return service;  
  19.   
  20.         functiongetData() {}  
  21.     }  
  22. })();  
Change this code to create our service and get our API data.

Here we create our Service as StudentService and get the result from our WEB API method and bind to APIData.
  1. (function()  
  2.  {  
  3.     'use strict';  
  4.   
  5.     varstudentService = angular.module('studentService', ['ngResource']);  
  6.     studentService.factory('student', ['$resource',  
  7.         function($resource)  
  8.       {  
  9.             alert("hi");  
  10.             return $resource('/api/StudentMasters/', {}, {  
  11.   
  12.                 APIData:  
  13.                 {  
  14.                     method: 'GET',  
  15.                     params: {},  
  16.                     isArray: true  
  17.                 }  
  18.   
  19.             });  
  20.             alert("hi12");  
  21.         }  
  22.     ]);  
  23. })();  
Creating AngularJS Controller:

Now we will create a new AngularJsControllerunder Controllers folder inside Scripts folder.
Right click our Controllers folder under Scripts folder and clicks add new Item ,Select Client-Side and Select AngularJs Factory and click Add.

controller

Now we can see the default code will be look like this below.
  1. (function()  
  2.  {  
  3.     'use strict';  
  4.   
  5.     angular  
  6.         .module('app')  
  7.         .controller('controller', controller);  
  8.   
  9.     controller.$inject = ['$location'];  
  10.   
  11.     function controller($location)  
  12.     {  
  13.         /* jshintvalidthis:true */  
  14.         varvm = this;  
  15.         vm.title = 'controller';  
  16.   
  17.         activate();  
  18.   
  19.         function activate() {}  
  20.     }  
  21. })();  
Change this code to create our Controller and get our API data from AngularJsServicde and store to $scope.student for binding in our MVC view.
  1. (function()  
  2.  {  
  3.     'use strict';  
  4.   
  5.     angular  
  6.         .module('studentapp')  
  7.         .controller('studentController', studentController);  
  8.   
  9.     studentController.$inject = ['$scope''student'];  
  10.   
  11.     functionstudentController($scope, student)  
  12.     {  
  13.   
  14.         $scope.student = student.APIData();  
  15.     }  
  16. })();  
Note: Nowagain open the Tast Runner Explorer and select the default under Gruntfile.js .

Right click and run it. We can see as “1 file created”.

explorer

Now we can see app.js file will be created in our wwwroot.And also all our AngularJS Module,Service and Conroller script will be added for displaying our data.

code

Design MVC View page, Run and Output.

Here I have bind the AngularJs controller result to our detaul home index View.

home

I have changed the default index.cshtml page to below html deign to bind our AngularJS controller Student data to our view.
  1. <htmlng-app="studentapp">  
  2.     @{ ViewBag.Title = "ASP.NET5"; }  
  3.   
  4.     <head>  
  5.   
  6.   
  7.     </head>  
  8.   
  9.     <bodyng-controller="studentController">  
  10.   
  11.         <tablewidth="99%" style="border-bottom:3pxsolid#3273d5;">  
  12.             <tr>  
  13.   
  14.                 <tdwidth="190">  
  15.                     <tablewidth="99%">  
  16.                         <tr>  
  17.                             <td>  
  18.                                 Welcome Mr. {{'SHANU'}}  
  19.   
  20.                             </td>  
  21.   
  22.   
  23.                         </tr>  
  24.                         </table>  
  25.                         </td>  
  26.                         <tdclass="style1" align="center">  
  27.                             <h3>Shanu - ASP.NET Core 1.0 MVC 6 with WEB API and AngularJS :)</h3>  
  28.   
  29.   
  30.                             </td>  
  31.   
  32.             </tr>  
  33.             </table>  
  34.   
  35.             <tablestyle="width: 99%; background-color:#FFFFFF; border solid 2px #6D7B8D; padding 5px;width 99%;table-layout:fixed;" cellpadding="2" cellspacing="2">  
  36.   
  37.                 <trstyle="height: 30px; background-color:#336699 ; color:#FFFFFF ;border: solid1px#659EC7;">  
  38.                     <tdwidth="40" align="center"><b>Student ID</b></td>  
  39.                         <tdwidth="100" align="center"><b>Student Name </b></td>  
  40.                             <tdwidth="120" align="center"><b>Email</b></td>  
  41.                                 <tdwidth="120" align="center"><b>Phone</b></td>  
  42.                                     <tdwidth="120" align="center"><b>Address</b></td>  
  43.   
  44.                                         </tr>  
  45.                                         <tbodydata-ng-repeat="details in student">  
  46.                                             <tr>  
  47.   
  48.                                                 <tdalign="center" style="border: solid1px#659EC7; padding: 5px;table-layout:fixed;">  
  49.                                                     <spanstyle="color:#9F000F">  
  50.                                                         {{details.StdID}}  
  51.                                                         </span>  
  52.                                                         </td>  
  53.   
  54.                                                         <tdalign="center" style="border: solid1px#659EC7; padding: 5px;table-layout:fixed;">  
  55.                                                             <spanstyle="color:#9F000F">  
  56.                                                                 {{details.StdName}}  
  57.                                                                 </span>  
  58.                                                                 </td>  
  59.   
  60.                                                                 <tdvalign="top" style="border: solid1px#659EC7; padding: 5px;table-layout:fixed;">  
  61.                                                                     <spanstyle="color:#9F000F">  
  62.                                                                         {{details.Email}}  
  63.                                                                         </span>  
  64.                                                                         </td>  
  65.   
  66.                                                                         <tdvalign="top" style="border: solid1px#659EC7; padding: 5px;table-layout:fixed;">  
  67.                                                                             <spanstyle="color:#9F000F">  
  68.                                                                                 {{details.Phone}}  
  69.                                                                                 </span>  
  70.                                                                                 </td>  
  71.                                                                                 <tdvalign="top" style="border: solid1px#659EC7; padding: 5px;table-layout:fixed;">  
  72.                                                                                     <spanstyle="color:#9F000F">  
  73.                                                                                         {{details.Address}}  
  74.                                                                                         </span>  
  75.                                                                                         </td>  
  76.                                             </tr>  
  77.                                             </tbody>  
  78.                                             </table>  
  79.   
  80.   
  81.                                             </body>  
  82.   
  83.                                             </html>  
  84.   
  85.   
  86.                                             <scriptsrc="//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js">  
  87.                                                 </script>  
  88.                                                 <scriptsrc="//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-resource.js">  
  89.                                                     </script>  
  90.                                                     <scriptsrc="~/app.js">  
  91.                                                         </script>  
Run the Program:

Here we can see all the data from WEB API has been bind to our MVC View using AngularJS.

output

Read more articles on ASP.NET Core: