Share via


ASP.NET Core 1.0 MVC 6 using WEB API and AngularJS

 

You can download the Source Code from this link: Download Source Code 

Introduction

https://gallery.technet.microsoft.com/site/view/file/149348/1/0.PNG

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

View our Previous article ASP.NET 5 CRUD using Scaffolding and Entity Framework

Prerequisites

Visual Studio 2015: You can download it from here.

ASP.NET 5 /Core 1.0: download ASP.NET 5 RC from this link https://get.asp.net/ 

In this article we will see in detail of 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 a 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 binding in an 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 as StudentsDB and a table as StudentMaster. Here is the SQL script to create Database table and sample record insert query in our table.

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]

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 New, then Project, select Web and select ASP.NET Web Application. Enter your Project Name and click OK.

https://gallery.technet.microsoft.com/site/view/file/149349/1/1.PNG

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

https://gallery.technet.microsoft.com/site/view/file/149350/1/2.PNG

Database Connection String:

Now we need to change the local connection string from our 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 in our ASP.NET 5 solution.

https://gallery.technet.microsoft.com/site/view/file/149351/1/3.PNG

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 below by default.

https://gallery.technet.microsoft.com/site/view/file/149352/1/4.PNG

Now the default connectionstring will be something like this:

"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:

"ConnectionString":  "Server=YourSQLSERVERNAME;Database=StudentsDB;user id=SQLID;password=;Trusted_Connection=True;MultipleActiveResultSets=true;"

Creating our Model

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

https://gallery.technet.microsoft.com/site/view/file/149353/1/6.PNG

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

https://gallery.technet.microsoft.com/site/view/file/149354/1/7.PNG

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

https://gallery.technet.microsoft.com/site/view/file/149355/1/8.PNG

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

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Threading.Tasks; 
using System.ComponentModel.DataAnnotations; 
  
namespace MYASP.NET5DemoTest.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; } 
    } 
}

Now we have created our Model, the next step is to add DBContext for our model. 

Creating DbContext

Now we need to create a DBContext for our Entity Framework. Like the 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” 

https://gallery.technet.microsoft.com/site/view/file/149356/1/9.PNG

Here our class will be look like below image.
 

https://gallery.technet.microsoft.com/site/view/file/149357/1/10.PNG 

First we need to add the header file for Entity Framework as using Microsoft.Data.Entity;

Next, inherit the DbContext to our class and create the object for our DBContext like below code.

using System.Collections.Generic; 
using System.Linq; 
using System.Threading.Tasks; 
using Microsoft.Data.Entity; 
  
namespace MYASP.NET5DemoTest.Models 
{ 
    public class  StudentMastersAppContext : DbContext 
    { 
        public DbSet<StudentMasters> Students { get; set; } 
    } 
}

Now we can created our DBcontext 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 . 

https://gallery.technet.microsoft.com/site/view/file/149358/1/11.PNG 

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

https://gallery.technet.microsoft.com/site/view/file/149359/1/12.PNG

Now we can add one more DBContext for our StudentMastersAppContext like below code.

// Add Entity Framework 
            services.AddEntityFramework() 
                   .AddSqlServer() 
                   .AddDbContext<StudentMastersAppContext>(options => 
                       options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

In ConfigureServices method we add like this code below.

public void  ConfigureServices(IServiceCollection services) 
        { 
            // Add framework services. 
            services.AddEntityFramework() 
                .AddSqlServer() 
                .AddDbContext<ApplicationDbContext>(options => 
                    options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"])); 
  
            services.AddIdentity<ApplicationUser, IdentityRole>() 
                .AddEntityFrameworkStores<ApplicationDbContext>() 
                .AddDefaultTokenProviders(); 
  
            services.AddMvc(); 
  
            // Add Entity Framework 
            services.AddEntityFramework() 
                   .AddSqlServer() 
                   .AddDbContext<StudentMastersAppContext>(options => 
                       options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"])); 
  
            // Add application services. 
            services.AddTransient<IEmailSender, AuthMessageSender>(); 
            services.AddTransient<ISmsSender, AuthMessageSender>(); 
        }

Next step is to add WEBAPI Controller.

Creating our WEBAPI Controller

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

https://gallery.technet.microsoft.com/site/view/file/149360/1/13.PNG

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”.

https://gallery.technet.microsoft.com/site/view/file/149361/1/14.PNG

Give our Controller name with API and click Add.

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.

https://gallery.technet.microsoft.com/site/view/file/149362/1/16.PNG

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”.

https://gallery.technet.microsoft.com/site/view/file/149363/1/17.PNG

Now we create one more folders for our AngularJS controller named “Controllers”.

https://gallery.technet.microsoft.com/site/view/file/149364/1/18.PNG

Adding a Grunt package using NPM Configuration File

Now we need to add a NPM Configuration File for adding a Grunt package to run our JavaScript files.

As we have created as a Web Application, the NPM Configuration File will be located in our project.

https://gallery.technet.microsoft.com/site/view/file/149365/1/19.PNG

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”.

https://gallery.technet.microsoft.com/site/view/file/149366/1/20.PNG

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

https://gallery.technet.microsoft.com/site/view/file/149367/1/21.PNG

Dependencies Folder:

https://gallery.technet.microsoft.com/site/view/file/149368/1/24.PNG

In the dependency folder we can see the entire installed NPM package. Here we can see by default Grunt package has been not 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.

https://gallery.technet.microsoft.com/site/view/file/149370/1/22.PNG

Now open the “package.JSON” file. 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.

https://gallery.technet.microsoft.com/site/view/file/149371/1/23.PNG

Here we have changed the name as our Solution name and also added the Grunt package.

{ 
  "name": "testforDemo", 
  "version": "0.0.0",  
  "devDependencies": { 
    "gulp": "3.8.11",  
    "gulp-concat": "2.5.2",  
    "gulp-cssmin": "0.1.7",  
    "gulp-uglify": "1.2.0",  
    "rimraf": "2.2.8",  
    "grunt": "0.4.5",  
    "grunt-contrib-uglify": "0.9.1",  
    "grunt-contrib-watch": "0.6.1"
  } 
}

After adding the Grunt file save the file. Now we can see in the Dependencies folder.

Save the package.json file and you should be able to see a Grunt package under Dependencies/ npm Folder.

https://gallery.technet.microsoft.com/site/view/file/149372/1/25.PNG

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

https://gallery.technet.microsoft.com/site/view/file/149373/1/26.PNG

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

https://gallery.technet.microsoft.com/site/view/file/149374/1/27.PNG

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.

https://gallery.technet.microsoft.com/site/view/file/149375/1/28.PNG

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

https://gallery.technet.microsoft.com/site/view/file/149376/1/29.PNG

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

https://gallery.technet.microsoft.com/site/view/file/149377/1/30.PNG

Next we configure the Grunt. Add the app.js file in our wwwroot folder. 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.

module.exports = function  (grunt) { 
    grunt.loadNpmTasks('grunt-contrib-uglify'); 
    grunt.loadNpmTasks('grunt-contrib-watch'); 
  
    grunt.initConfig({ 
        uglify: { 
            my_target: { 
                files: { 'wwwroot/app.js': ['Scripts/app.js', 'Scripts/**/*.js'] } 
            } 
        }, 
  
        watch: { 
            scripts: { 
                files: ['Scripts/**/*.js'], 
                tasks: ['uglify'] 
            } 
        } 
    }); 
  
    grunt.registerTask('default', ['uglify', 'watch']);  
};

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 Runner, click the menu View > Other Windows > and click Task Runner Explorer.

https://gallery.technet.microsoft.com/site/view/file/149378/1/31.PNG

Now we can see our Task Runner Explorer.

https://gallery.technet.microsoft.com/site/view/file/149379/1/32.PNG

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

https://gallery.technet.microsoft.com/site/view/file/149381/1/33.PNG

Now we can see all Gruntfile has been added.

https://gallery.technet.microsoft.com/site/view/file/149382/1/34.PNG

Right click the default under Alias Task and click Run.

https://gallery.technet.microsoft.com/site/view/file/149383/1/35.PNG

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.

https://gallery.technet.microsoft.com/site/view/file/149384/1/36.PNG

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.

https://gallery.technet.microsoft.com/site/view/file/149385/1/37.PNG

Change the code with our Module Name and service name for calling WEB API and binding from Controller.

(function () { 
    'use strict'; 
  
    angular.module('studentapp', [ 
        // Angular modules  
        'studentService'
  
        // Custom modules  
  
        // 3rd Party Modules 
          
    ]); 
})();

Creating AngularJs Service:

Now we will create a new AngularJs Service under 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.

https://gallery.technet.microsoft.com/site/view/file/149386/1/38.PNG

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. 

(function () { 
    'use strict'; 
  
    var studentService = angular.module('studentService', ['ngResource']); 
    studentService.factory('student', ['$resource', 
        function ($resource) { 
            alert("hi"); 
            return $resource('/api/StudentMasters/', {}, { 
  
                APIData: { method: 'GET', params: {}, isArray: true  } 
  
            }); 
            alert("hi12"); 
        } 
    ]); 
})();

Creating AngularJs Controller:

Now we will create a new AngularJs Controller under 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.

https://gallery.technet.microsoft.com/site/view/file/149387/1/39.PNG

Change this code to create our Controller and get our API data from AngularJs Servicde and store to $scope.student for binding in our MVC view.

(function () { 
    'use strict'; 
  
    angular 
        .module('studentapp') 
        .controller('studentController', studentController); 
  
    studentController.$inject = ['$scope', 'student'];  
  
    function studentController($scope, student) { 
       
        $scope.student = student.APIData(); 
    } 
})();

**Note: **Again, open the Tast Runner Explorer and select the default under Gruntfile.js.

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

https://gallery.technet.microsoft.com/site/view/file/149388/1/40.PNG

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

https://gallery.technet.microsoft.com/site/view/file/149389/1/41.PNG

Design MVC View page, Run and Output.

Here we have bind the AngularJs controller result to our default home index View.

https://gallery.technet.microsoft.com/site/view/file/149390/1/42.PNG

We have changed the default index.cshtml page to below HTML design to bind our AngularJS controller Student data to our view.

<html ng-app="studentapp"> 
@{ 
    ViewBag.Title = "ASP.NET5"; 
} 
<head> 
  
  
</head> 
  
<body ng-controller="studentController"> 
  
    <table width="99%" style=" border-bottom:3px solid #3273d5;"> 
        <tr> 
  
            <td width="190"> 
                <table width="99%"> 
                    <tr> 
                        <td> 
                            Welcome Mr. {{'SHANU'}} 
  
                        </td> 
  
  
                    </tr> 
                </table> 
            </td> 
            <td class="style1" align="center"> 
                <h3>Shanu - ASP.NET Core 1.0 MVC 6 with WEB API and AngularJS :)</h3> 
  
  
            </td> 
              
        </tr> 
    </table> 
  
    <table style="width: 99%; background-color:#FFFFFF; border solid 2px #6D7B8D; padding 5px;width 99%;table-layout:fixed;" cellpadding="2" cellspacing="2"> 
  
        <tr style="height: 30px; background-color:#336699 ; color:#FFFFFF ;border: solid 1px #659EC7;"> 
            <td width="40" align="center"><b>Student ID</b></td> 
            <td width="100" align="center"><b>Student Name </b></td> 
            <td width="120" align="center"><b>Email</b></td> 
            <td width="120" align="center"><b>Phone</b></td> 
            <td width="120" align="center"><b>Address</b></td> 
  
        </tr> 
        <tbody data-ng-repeat="details in student"> 
            <tr> 
  
                <td align="center" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;"> 
                    <span style="color:#9F000F"> 
                        {{details.StdID}} 
                    </span> 
                </td>              
  
                <td align="center" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;"> 
                    <span style="color:#9F000F"> 
                        {{details.StdName}} 
                    </span> 
                </td> 
  
                <td valign="top" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;"> 
                    <span style="color:#9F000F"> 
                        {{details.Email}} 
                    </span> 
                </td> 
  
                <td valign="top" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;"> 
                    <span style="color:#9F000F"> 
                        {{details.Phone}} 
                    </span> 
                </td> 
                <td valign="top" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;"> 
                    <span style="color:#9F000F"> 
                        {{details.Address}} 
                    </span> 
                </td> 
            </tr> 
        </tbody> 
    </table> 
  
  
</body> 
</html> 
  
  
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"></script> 
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-resource.js"></script> 
<script src="~/app.js"></script>

Run the Program:

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

https://gallery.technet.microsoft.com/site/view/file/149348/1/0.PNG