ASP.NET Development Company in USA

** ### Need some work done on your website? ** **Data EximIT** is the one of the Top [**ASP. NET Development Company in USA**](https://www.dataeximit.com/asp-net-development-services/ "ASP. NET Development Company in USA"), dominates the software...

Need some work done on your website?

Data EximIT is the one of the Top ASP. NET Development Company in USA, dominates the software development arena with the power of Microsoft .NET tools by taking advantage of the key features of this very versatile platform Efficient code management practices, simplistic programming model, service-oriented architecture, easy deployment, and maintainability.

TRANSFORM YOUR ORDINARY WEBSITE INTO EXTRAORDINARY AS Data EximIT ADD WOW FACTOR TO IT!

Start a Conversation Today

ASP.NET MVC Application with JQuery, AJAX

ASP.NET MVC Application with JQuery, AJAX

Let's have a sample example: We have a submit button in our JQuery AJAX MVC application. Let's try to show a message when it is clicked. ASP.NET MVC Application - Using JQuery, AJAX

Before diving into the core topic let’s have an overview about JQuery and Ajax. What is it?

What is JQuery?
Well, JQuery is a framework (tools) for writing JavaScript, Written as "write less, do more", jQuery is to make easier to use JavaScript.

What is JavaScript?
JavaScript is an object-oriented computer programming (Scripting) language commonly used to create interactive effects within web browsers.

Let’s have a sample example:
We have a submit button in our JQuery AJAX MVC application. Let’s try to show a message when it is clicked.

Here is our button with defined id="btnSubmit":

<input type="submit" value="Create" class="btn btn-default" id="btnSubmit" />

Now we need to write some script to do that, here is some JavaScript code:

var myBtn = document.getElementById('btnSubmit');  
myBtn.addEventListener('click', function(e) {  
    e.preventDefault(); //This prevents the default action  
    alert('Hello'); //Show the alert  
});

By this code the result will show “Hello”:

Now if we can get the same result by using jQuery instead of it. Let’s have a look:

$('#btnSubmit').click(function(event) {  
    event.preventDefault(); //This prevents the default action  
    alert("Hello"); //Show the alert  
});

Note: Here use of 'e' is just a short for event which raised the event. We can pass any variable name. Notice that the ‘e’ is changed to name ‘event’ in JQuery part.

This piece of code is also producing the same result “Hello”. This is why jQuery is known as "write less, do more".

Finally the script:

<script type="text/javascript">  
    $(document).ready(function() {  
        $(function() {  
  
            /*var myBtn = document.getElementById('btnSubmit');  
            myBtn.addEventListener('click', function(e) {  
                e.preventDefault();  
                alert('Hello');  
            });*/
  
            $('#btnSubmit').click(function(event) {  
                event.preventDefault();  
                alert("Hello");  
            });  
        });  
    });  
</script>

Let's focus on Ajax:

AJAX stands for “Asynchronous JavaScript and XML”. AJAX is about exchanging data with a server, without reloading the whole page. It is a technique for creating fast and dynamic web pages.

In .NET, we can call server side code using two ways:

  1. ASP .NET AJAX
  2. jQuery AJAX

In this article we will focus on JQuery Ajax.

$.ajax () Method:

JQuery’s core method for creating Ajax requests. Here are some jQuery AJAX methods:

  • $.ajax() Performs an async AJAX request.
  • $.get() Loads data from a server using an AJAX HTTP GET request.
  • $.post() Loads data from a server using an AJAX HTTP POST request.

To know more click.

$.ajax () Method Configuration option:

Options that we use:

  • async:
  • type:
  • url:
  • data:
  • datatype:
  • success:
  • error:

Let’s have details overview:

async

Set to false if the request should be sent synchronously. Defaults to true.

Note that if you set this option to false, your request will block execution of other code until the response is received.

Example:

async: false,

type

This is type of HTTP Request and accepts a valid HTTP verb.

The type of the request, "POST" or "GET" defaults to "GET". Other request types, such as "PUT" and "DELETE" can be used, but they may not be supported by all the web browsers.

Example:

type: "POST",

url

The URL for the request.

Example:

url: "/Home/JqAJAX",

data

The data to be sent to the server. This can either be an object or a query string.

Example:

data: JSON.stringify(model_data),

dataType

The type of data you expect back from the server. By default, jQuery will look at the MIME type of the response if no dataType is specified.

Accepted values are text, xml, json, script, html jsonp.

Example:

dataType: "json",

contentType

This is the content type of the request you are making. The default is 'application/x-www-form-urlencoded'.

Example:

contentType: 'application/json; charset=utf-8',

success

A callback function to run if the request succeeds. The function receives the response data (converted to a JavaScript object if the DataType was JSON), as well as the text status of the request and the raw request object.

Success: function (result) {  
   $('#result').html(result);  
}

error

A callback function to run if the request results in an error. The function receives the raw request object and the text status of the request.

error: function (result) {  
   alert('Error occured!!');  
},

Let’s Post Values using JQuey,Ajax:

We often use the jQuery Ajax method in ASP.NET Razor Web Pages. Here is a sample code:

<input type="submit" id="btnSubmit" value="Add Student" />  
<script type="text/javascript">  
    $(document).ready(function() {  
        $(function() {  
            $('#btnSubmit').click(function(event) {  
                event.preventDefault();  
                var Student = {  
                    ID: '10001',  
                    Name: 'Shashangka',  
                    Age: 31  
                };  
                $.ajax({  
                    type: "POST",  
                    url: "/Home/JqAJAX",  
                    data: JSON.stringify(Student),  
                    dataType: "json"  
                    contentType: 'application/json; charset=utf-8',  
                    success: function(data) {  
                        alert(data.msg);  
                    },  
                    error: function() {  
                        alert("Error occured!!")  
                    }  
                });  
            });  
        });  
    });  
</script>

Controller Action:

// GET: Home/JqAJAX  
[HttpPost]  
public ActionResult JqAJAX(Student st) {  
    try {  
        return Json(new {  
            msg = "Successfully added " + st.Name  
        });  
    } catch (Exception ex) {  
        throw ex;  
    }  
}

Posting JSON

JSON is a data interchange format where values are converted to a string. The recommended way to create JSON is include the JSON.stringify method. In this case we have defined:

JSON.stringify(Student)

And the data type set to:

datatype: "json"

And the content type set to application/json

contentType: 'application/json; charset=utf-8'

Syntax:

JSON.stringify(value[, replacer[, space]])

Post Script:

var Student = {  
    ID: '10001',  
    Name: 'Shashangka',  
    Age: 31  
};  
$.ajax({  
    type: "POST",  
    url: "/Home/JqAJAX",  
    data: JSON.stringify(Student),  
    contentType: 'application/json; charset=utf-8',  
    success: function(data) {  
        alert(data.msg);  
    },  
    error: function() {  
        alert("Error occured!!")  
    }  
});

Controller Action:

// GET: Home/JqAJAX  
[HttpPost]  
public ActionResult JqAJAX(Student st) {  
    try {  
        return Json(new {  
            msg = "Successfully added " + st.Name  
        });  
    } catch (Exception ex) {  
        throw ex;  
    }  
}

JSON Response Result:
Sent data format:
{"ID":"10001","Name":"Shashangka","Age":31}
Received Data format:
{"msg":"Successfully added Shashangka"}

Let’s Post JavaScript Objects:

To send JavaScript Objects we need to omit the JSON.stringify(Student) method and we need to pass the plain object to the data option. In this case we have defined:

data: Student

And the datatype set to:

datatype: "html"

And the content type set to default.

contentType: 'application/x-www-form-urlencoded'

Post Script

var Student = {  
    ID: '10001',  
    Name: 'Shashangka',  
    Age: 31  
};  
$.ajax({  
    type: "POST",  
    url: "/Home/JqAJAX",  
    data: Student,  
    contentType: 'application/x-www-form-urlencoded',  
    datatype: "html",  
    success: function(data) {  
        alert(data.msg);  
    },  
    error: function() {  
        alert("Error occured!!")  
    }  
});

Controller Action:

var Student = {  
    ID: '10001',  
    Name: 'Shashangka',  
    Age: 31  
};  
$.ajax({  
    type: "POST",  
    url: "/Home/JqAJAX",  
    data: Student,  
    contentType: 'application/x-www-form-urlencoded',  
    datatype: "html",  
    success: function(data) {  
        alert(data.msg);  
    },  
    error: function() {  
        alert("Error occured!!")  
    }  
});

JavaScript Objects Response Result:

Sent data format:
ID=10001&Name=Shashangka&Age=31
Received Data format:
{"msg":"Successfully added Shashangka"}

Let’s Post JavaScript Arrays:

To send Array we need to omit the JSON.stringify(Student) method and we need to pass the plain object to the data option. In this case we have defined:

data: Student

And the datatype set to:

datatype: "html"

And the content type set to default

contentType: 'application/x-www-form-urlencoded'

Post Script:

var ID = ["Shashangka", "Shekhar", "Mandal"];  
  
$.ajax({  
    type: "POST",  
    url: "/Home/JqAJAX",  
    data: {  
        values: ID  
    },  
    datatype: "html",  
    contentType: 'application/x-www-form-urlencoded',  
    success: function(data) {  
        alert(data.msg);  
    },  
    error: function() {  
        alert("Error occured!!")  
    }  
});

Controller Action:

// GET: Home/JqAJAX  
[HttpPost]  
public ActionResult JqAJAX(string[] values) {  
    try {  
        return Json(new {  
            msg = String.Format("Fist Name: {0}", values[0])  
        });  
    } catch (Exception ex) {  
        throw ex;  
    }  
}

Array Response Result:

Sent data format:
values[]=Shashangka&values[]=Shekhar&values[]=Mandal
Received Data format:
{"msg":"Fist Name: Shashangka"}

Hope this will help to understand different datatypes and Ajax posting. Thank you!

Using Parcel.js in an ASP.NET Core Application

Using Parcel.js in an ASP.NET Core Application

In this post, we’re going to take an ASP.NET website template that uses Bootstrap 4 and set it up to use Parcel-generated bundles instead.

In this post, we’re going to take an ASP.NET website template that uses Bootstrap 4 and set it up to use Parcel-generated bundles instead.

Parcel.js is a “Blazing fast, zero configuration web application bundler.” In this post, we’re going to take an ASP.NET Core website template that uses Bootstrap 4 and set it up to use Parcel-generated bundles instead.

ASP.NET Core supports bundling and minifying static assets at design-time using the community supported BuildBundlerMinifier package that can be configured in a bundleconfig.json file. However it’s not well suited for scenarios that would benefit from a deploy-time bundling strategy, i.e. assets are built during deployment and output files are not checked in.

This is where Parcel.js comes in. Parcel is a “Blazing fast, zero configuration web application bundler.” The zero-configuration bit is its major selling point because it allows you to get started with minimal effort.

In this post, we’re going to take an ASP.NET website template that uses Bootstrap 4 and set it up to use Parcel-generated bundles instead.

Create & Set Up a New ASP.NET Project

  1. Create a web project that uses Razor Pages. To do this on the command line, run:
  2. dotnet new webapp --name AspNetParcelExp cd AspNetParcelExp
  3. Delete the folders under wwwroot. (You may delete this later on, if you want it for reference — our goal is to generate these files using Parcel and use those instead.)
  4. Install npm Dependencies
  5. Add a package.json file to the project root like the following:
 	{
  "name": "aspnet-parcel-exp",
  "private": true,
  "version": "0.1.0"
}


  1. Create a web project that uses Razor Pages. To do this on the command line, run:
  2. dotnet new webapp --name AspNetParcelExp cd AspNetParcelExp
  3. Delete the folders under wwwroot. (You may delete this later on, if you want it for reference — our goal is to generate these files using Parcel and use those instead.)
  4. Install npm Dependencies
  5. Add a package.json file to the project root like the following:
javascriptnpm install --save-dev [email protected]

  1. Create a web project that uses Razor Pages. To do this on the command line, run:
  2. dotnet new webapp --name AspNetParcelExp cd AspNetParcelExp
  3. Delete the folders under wwwroot. (You may delete this later on, if you want it for reference — our goal is to generate these files using Parcel and use those instead.)
  4. Install npm Dependencies
  5. Add a package.json file to the project root like the following:
npm install [email protected]
npm install [email protected]
npm install [email protected]
npm install [email protected]
npm install [email protected]

If everything went right, your package.json should look something like this:

{
  "name": "aspnet-parcel-exp",
  "private": true,
  "version": "0.1.0",
  "devDependencies": {
    "parcel-bundler": "^1.11.0"
  },
  "dependencies": {
    "bootstrap": "^4.2.1",
    "jquery": "^3.3.1",
    "jquery-validation": "^1.19.0",
    "jquery-validation-unobtrusive": "^3.2.11",
    "popper.js": "^1.14.7"
  }
}


Set Up an Asset Bundle Using Parcel.js

  1. Create a web project that uses Razor Pages. To do this on the command line, run:
  2. dotnet new webapp --name AspNetParcelExp cd AspNetParcelExp
  3. Delete the folders under wwwroot. (You may delete this later on, if you want it for reference — our goal is to generate these files using Parcel and use those instead.)
  4. Install npm Dependencies
  5. Add a package.json file to the project root like the following:
 	/AspNetParcelExp/ # project root
  - .sassrc       # sass configuration
  - assets/       # front end assets root
    - scss/       # Place for all styles
      - site.scss
    - js/         # Place for all scripts
      - site.js
    - bundle.js   # Entry point for our output bundle


  1. Create a web project that uses Razor Pages. To do this on the command line, run:
  2. dotnet new webapp --name AspNetParcelExp cd AspNetParcelExp
  3. Delete the folders under wwwroot. (You may delete this later on, if you want it for reference — our goal is to generate these files using Parcel and use those instead.)
  4. Install npm Dependencies
  5. Add a package.json file to the project root like the following:
// Import styles  
import './scss/site.scss'  

// Setup jquery
import $ from 'jquery'
window.$ = window.jQuery = $

// Import other scripts
import 'bootstrap'  
import 'jquery-validation'  
import 'jquery-validation-unobtrusive'  

import './js/site'


We import everything we depend on. ‘bootstrap’ for example refers to the …/node_modules/bootstrap/ folder. If you want to import a specific file from a package only, you may do that too. The above code should be straightforward, except for maybe jQuery, which I’ll explain in a bit.

  1. Create a web project that uses Razor Pages. To do this on the command line, run:
  2. dotnet new webapp --name AspNetParcelExp cd AspNetParcelExp
  3. Delete the folders under wwwroot. (You may delete this later on, if you want it for reference — our goal is to generate these files using Parcel and use those instead.)
  4. Install npm Dependencies
  5. Add a package.json file to the project root like the following:
 	{
  "includePaths": [
    "./node_modules/"
  ]
}


This will allow referencing package folders without a full path to it. See parcel-bundler/parcel#39 for more information.

  1. Create a web project that uses Razor Pages. To do this on the command line, run:
  2. dotnet new webapp --name AspNetParcelExp cd AspNetParcelExp
  3. Delete the folders under wwwroot. (You may delete this later on, if you want it for reference — our goal is to generate these files using Parcel and use those instead.)
  4. Install npm Dependencies
  5. Add a package.json file to the project root like the following:
 	@import "~bootstrap/scss/bootstrap";


You may also just include the bootstrap SCSS files that you actually need to keep the output size down. Since we’re trying to replicate the template, we could also paste the code in the original template’s site.css here after the line.

  1. Create a web project that uses Razor Pages. To do this on the command line, run:
  2. dotnet new webapp --name AspNetParcelExp cd AspNetParcelExp
  3. Delete the folders under wwwroot. (You may delete this later on, if you want it for reference — our goal is to generate these files using Parcel and use those instead.)
  4. Install npm Dependencies
  5. Add a package.json file to the project root like the following:
 	"scripts": {
  "build": "parcel build assets/bundle.js --out-dir wwwroot/dist/",
  "watch": "parcel watch assets/bundle.js --out-dir wwwroot/dist/"
},

This adds scripts that can be invoked as npm run build to build, for example. It passes the bundle.js entry point to Parcel, and instructs it to generate output files in the wwwroot/dist/ using the --out-dir option.

  1. Create a web project that uses Razor Pages. To do this on the command line, run:
  2. dotnet new webapp --name AspNetParcelExp cd AspNetParcelExp
  3. Delete the folders under wwwroot. (You may delete this later on, if you want it for reference — our goal is to generate these files using Parcel and use those instead.)
  4. Install npm Dependencies
  5. Add a package.json file to the project root like the following:
npm run build

You should now see a bundle.css, bundle.js and a bundle.map file in the wwwroot/dist directory (the directory we specified for the build script above). It’s a good idea to ignore the wwwroot/dist from version control.

  1. Create a web project that uses Razor Pages. To do this on the command line, run:
  2. dotnet new webapp --name AspNetParcelExp cd AspNetParcelExp
  3. Delete the folders under wwwroot. (You may delete this later on, if you want it for reference — our goal is to generate these files using Parcel and use those instead.)
  4. Install npm Dependencies
  5. Add a package.json file to the project root like the following:
 	<script src="~/dist/bundle.js" 
        asp-append-version="true"></script>
 	And replace the stylesheet <link> tags with:
 	<link rel="stylesheet" 
      href="~/dist/bundle.css" 
      asp-append-version="true" />


That’s it. If you did everything right, running the program should display the same output as with the old files.

If it feels like a lot of work, it’s probably because you aren’t familiar with the npm, SCSS, etc., so take your time.

Watching Changes

Rather than running npm run build each time you make changes, you can use HMR (Hot Module Replacement), which will detect pages and reload for you, so that you don’t have to do it.

Open a new terminal instance and run npm run watch. Keep this running while performing any dev changes — it’ll speed you up.

Add a Pre-Publish Task

Add the following to the AspNetParcelExp.csproj file right before the closing

</Project> tag:
<Target Name="ParcelBeforePublish" 
        BeforeTargets="PrepareForPublish">
  <Exec Command="npm run build" />
</Target>


Now, every time you create a publish package, it will run the npm build script. This is particularly important in Continuous Delivery scenarios, because the wwwroot/dist is (usually) not under version control, and the build environment needs to build the files before deploying. You may test this step using dotnet publish: you’ll see output from parcel-bundler.

If you want the task to be run every time is the project is built, change PrepareForPublish to BeforeBuild.

A Note on CommonJS Modules

The parcel-bundler generates a CommonJS module, which means it doesn’t pollute the global window object. Now this can be a problem sometimes, because some libraries — particularly the old ones — have always been polluting window.

Take jQuery for instance. Libraries that require jQuery perform a test on the window object to check if it’s got a jQuery or a $ property. Since CommonJS libraries don’t pollute window, these checks will fail. So we’ll need to manually pollute the window object ourselves. We did that for jquery in bundle.js using:

import $ from 'jquery'
window.$ = window.jQuery = $

This is one thing you need to remember when using Parcel.js or other similar bundlers.

A few pointers and ideas

  • You do not have to use SCSS. LESS or even plain CSS is completely fine.
  • Parcel.js doesn’t have a config file of its own, unlike Grunt or webpack. You may, however, have config files for each tool, and parcel-bundler will honor them. E.g. tsconfig.json for typescript, .sassrc for SCSS, etc.
  • Parce.js has built-in support for PostCSS. For example, to automatically add CSS prefixes to the generated output using the autoprefixer-postcss plugin, add the following to .postcssrc at the project root:
 	{ 
  "plugins": { 
    "autoprefixer": true 
  } 
}


  • You do not have to use SCSS. LESS or even plain CSS is completely fine.
  • Parcel.js doesn’t have a config file of its own, unlike Grunt or webpack. You may, however, have config files for each tool, and parcel-bundler will honor them. E.g. tsconfig.json for typescript, .sassrc for SCSS, etc.
  • Parce.js has built-in support for PostCSS. For example, to automatically add CSS prefixes to the generated output using the autoprefixer-postcss plugin, add the following to .postcssrc at the project root:

Build a Basic Website with ASP.NET MVC and Angular

Build a Basic Website with ASP.NET MVC and Angular

Build a Basic Website with ASP.NET MVC and Angular. Get Started with ASP.NET MVC. Create an Angular Project. Set up a Database for ASP.NET. Add Authentication to Your Angular Application. Set Up Your ASP.NET API Endpoints. Set a Default Formatter for ASP.NET Web API 2.

Build a Basic Website with ASP.NET MVC and Angular. Get Started with ASP.NET MVC. Create an Angular Project. Set up a Database for ASP.NET. Add Authentication to Your Angular Application. Set Up Your ASP.NET API Endpoints. Set a Default Formatter for ASP.NET Web API 2.

ASP.NET has been around for a long time. When Microsoft introduced ASP.NET MVC, it changed the way many developers approach their codebase. There is an excellent separation of concerns, a TDD friendly framework, and easy integration with JavaScript while maintaining full control over rendered HTML. On the client side, a lot of .NET developers prefer Angular because it comes with TypeScript and it’s a much closer language to C# than plain JavaScript. Angular is an excellent framework for building enterprise-level, feature rich, applications.

You will be using .NET Framework 4.7.1, and you should have the latest version of Visual Studio 2017 installed. Also, you should have Node and npm installed since you will use Angular tools that require Node and npm.

Get Started with ASP.NET MVC

Create an API using a built-in template within Visual Studio. You’ll start from a scratch.

In Visual Studio, select File -> New Project

Select Web, ASP.NET Web Application (.NET Framework)

On the following screen select MVC:

You should have a new ASP.NET MVC application ready now, with all the folders and files as shown in the following picture:

At this moment, in your project, you have some NuGet packages you won’t be using. You can get rid of them quite quickly. Run the following commands inside of your Package Manager Console

Uninstall-Package Microsoft.ApplicationInsights.Web
Uninstall-Package Microsoft.ApplicationInsights.WindowsServer
Uninstall-Package Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel
Uninstall-Package Microsoft.ApplicationInsights.PerfCounterCollector
Uninstall-Package Microsoft.ApplicationInsights.DependencyCollector
Uninstall-Package Microsoft.ApplicationInsights.Agent.Intercept
Uninstall-Package Microsoft.ApplicationInsights


Additionally, make sure you delete ApplicationInsights.config file.

After finishing, you should have a clean project and perfect starting ground.

Create an Angular Project

Using Angular CLI is the best way to get started with Angular applications. With Angular CLI tools, you can easily create new projects, update existing projects, add different components to your codebase, and do all of that by entering a few commands in your terminal. You can also run the application in the development environment and publish it to production environments. It saves you the trouble of setting up configuration and Webpack. It can also do all the optimizing, compressing and minifying for you. It’s highly recommended to use Angular CLI to prepare your applications for production environments.

You can install the Angular CLI by entering the following in your favorite terminal:

npm install -g @angular/[email protected]


After that, navigate to the folder of your MVC project and open your terminal there and enter the following:

ng new Angular --skip-tests --style=scss


This will create a new Angular project under Angular folder within your MVC project. The --skip-tests argument will make sure that CLI skips creating spec files.

You should include the Angular folder in your MVC project. To do that, click on the Show All Files button in your Solution Explorer. You can now navigate to Angular folder and include all folders and files except for node_modules. After you do that you should have a folder structure like on the following picture:

Set up a Database for ASP.NET

You will use Entity Framework (EF) 6 as your Object-Relational Mapper (ORM), a proven solution from Microsoft. EF 6 is pretty easy to set up and get going, and you don’t need to know any SQL to have it working for your applications. Think of it as an adapter or bridge to your database. All of your database queries will go through Entity Framework.

The central point is your DbContext class, and that’s where you define your connection string and the tables for your database. EF 6 uses the DbSet collection type to represent a table in a database. All you need to do is create a connection string, create a new class that inherits from DbContext, make the data models and create appropriate properties within DbContext for those models. Those properties will represent tables in the database. From that point, it’s pretty easy to get and update existing data by using Language Integrated Queries (LINQ).

You should first install the EF 6, by running the following code in the Package Manager Console:

Install-Package EntityFramework -Version 6.2.0


Add the Connection String

You can get started by adding a connection string to your Web.config file. Make sure to add it inside of the section, and after :

<connectionStrings>
  <add name="OktaConnectionString"
    connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=JoggingTracker;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\WeightTracker.mdf"
    providerName="System.Data.SqlClient"
  />
</connectionStrings>


Create Your DbContext and Data Models in Angular

First, create a model for a recording a jog. Create a file in the Models directory called JoggingRecord.cs:

using System;

namespace OktaAspNetMvcAngular.Models
{
  public class JoggingRecord
  {
    public int Id { get; set; }

    public float Distance { get; set; }

    public string Description { get; set; }

    public DateTime CreatedAt { get; set; }
  }
}


Nothing special here, a standard Id property that represents a unique identifier for every row within a table and Entity Framework will use a naming convention and automatically set it as a primary key for this table. You definitely need the Distance property to track your jogs, a Description to describe the jog and CreatedAt property for an audit trail.

Next, create an ApplicationDbContext class inside of a new folder called Data. For now, it will be pretty straightforward:

using System.Data.Entity;
using OktaAspNetMvcAngular.Models;

namespace OktaAspNetMvcAngular.Data
{
  public class ApplicationDbContext : DbContext
  {
    public ApplicationDbContext() : base("OktaConnectionString")
    {
    }

    public static ApplicationDbContext Create() => new ApplicationDbContext();

    public DbSet<JoggingRecord> JoggingRecords { get; set; }
  }
}


The piece of code that calls the base DbContext class is used to set up the connection string. There is the DbSet property that I previously mentioned, and it will be used to fetch records from the table, update and delete those records.

Enable and Run Migrations in Your ASP.NET Project

Open the Package Manager Console, and run the following to enable migrations:

Enable-Migrations


Now you can add your initial migration, which will contain the creation of the JoggingRecords table:

Add-Migration Initial


Now, you can update the database:

Update-Database -Verbose


The verbose flag will allow you to see the generated SQL statements, and this can help you in resolving errors if any occur.

Seed the Database

After you have updated the database, add Migrations by adding code inside of the Seed method in the Configuration class.

First, add the using for the Models namespace:

using OktaAspNetMvcAngular.Models;


After that, add the following code for the Seed method:

protected override void Seed(OktaAspNetMvcAngular.Data.ApplicationDbContext context)
{
  context.JoggingRecords.AddOrUpdate(x => x.Id,
    new JoggingRecord { Id = 1, Description = "Friday Evening", Distance = 5.5f, CreatedAt = new DateTime(2018, 5, 1) },
    new JoggingRecord { Id = 2, Description = "Saturday morning", Distance = 6.15f, CreatedAt = new DateTime(2018, 4, 4) },
    new JoggingRecord { Id = 3, Description = "Marathon", Distance = 20, CreatedAt = new DateTime(2018, 5, 13) },
    new JoggingRecord { Id = 4, Description = "Short one", Distance = 3.5f, CreatedAt = new DateTime(2018, 6, 6) }
  );

  //  This method will be called after migrating to the latest version.

  //  You can use the DbSet<T>.AddOrUpdate() helper extension method
  //  to avoid creating duplicate seed data.
}


Add Authentication to Your Angular Application

Handling the authentication is never an easy or comfortable task. If you want to quickly and easily take care of authentication for your application you’re likely in the market for a solution like Okta. That’s why so many developers love and use Okta, they never want to build auth again and are happy to leave it to us.

To get started with Okta, sign up for a forever-free developer account or (log in if you already have one).

You should see the Dashboard and in the upper right corner, there should be your unique Org URL. Save it for later.

Now you need to create a new application by browsing to the Applications tab and clicking Add Application, and from the first page of the wizard choose Single-Page App.

On the settings page, enter OktaMvcAngular as your name value and select Implicit(Hybrid).

Now that your application has been created copy down the Client ID and Client secret values on the following page, you’ll need them soon (of course, yours will be different).

It is quite easy to add authentication to ASP.NET MVC with help of Okta.

Add the following to your Web.config file, inside of :

<!-- 1\. Replace these values with your Okta configuration -->
<add key="okta:ClientId" value="{yourClientId}" />
<add key="okta:ClientSecret" value="{yourClientSecret}" />
<add key="okta:OrgUri" value="https://{yourOktaDomain}/oauth2/default" />

<!-- 2\. Update the Okta application with these values -->
<add key="okta:RedirectUri" value="http://localhost:8080/authorization-code/callback" />
<add key="okta:PostLogoutRedirectUri" value="http://localhost:8080/Account/PostLogout" />


Install the required NuGet packages:

Install-Package Okta.AspNet -Version 1.1.1 
Install-Package Microsoft.Owin.Host.SystemWeb -Version 4.0.0
Install-Package Microsoft.Owin.Security.Cookies -Version 4.0.0


Add the Startup class. Right click on the project -> Add new item -> OWIN Startup Class:

Replace the content of that file with the following code:

using IdentityModel.Client;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using Owin;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Security.Claims;
using System.Threading.Tasks;

[assembly: OwinStartup(typeof(OktaAspNetMvcAngular.Startup))]

namespace OktaAspNetMvcAngular
{
  public class Startup
  {
    // These values are stored in Web.config. Make sure you update them!
    private readonly string clientId = ConfigurationManager.AppSettings["okta:ClientId"];
    private readonly string redirectUri = ConfigurationManager.AppSettings["okta:RedirectUri"];
    private readonly string authority = ConfigurationManager.AppSettings["okta:OrgUri"];
    private readonly string clientSecret = ConfigurationManager.AppSettings["okta:ClientSecret"];
    private readonly string postLogoutRedirectUri = ConfigurationManager.AppSettings["okta:PostLogoutRedirectUri"];

    public void Configuration(IAppBuilder app)
    {
      // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
      app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
      app.UseCookieAuthentication(new CookieAuthenticationOptions());
      app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
      {
        ClientId = clientId,
        ClientSecret = clientSecret,
        Authority = authority,
        RedirectUri = redirectUri,
        ResponseType = OpenIdConnectResponseType.CodeIdToken,
        Scope = OpenIdConnectScope.OpenIdProfile,
        PostLogoutRedirectUri = postLogoutRedirectUri,
        TokenValidationParameters = new TokenValidationParameters
        {
          NameClaimType = "name"
        },

        Notifications = new OpenIdConnectAuthenticationNotifications
        {
          AuthorizationCodeReceived = async n =>
          {
            // Exchange code for access and ID tokens
            var tokenClient = new TokenClient(authority + "/v1/token", clientId, clientSecret);
            var tokenResponse = await tokenClient.RequestAuthorizationCodeAsync(n.Code, redirectUri);

            if (tokenResponse.IsError)
            {
              throw new Exception(tokenResponse.Error);
            }

            var userInfoClient = new UserInfoClient(authority + "/v1/userinfo");
            var userInfoResponse = await userInfoClient.GetAsync(tokenResponse.AccessToken);
            var claims = new List<Claim>();
            claims.AddRange(userInfoResponse.Claims);
            claims.Add(new Claim("id_token", tokenResponse.IdentityToken));
            claims.Add(new Claim("access_token", tokenResponse.AccessToken));

            if (!string.IsNullOrEmpty(tokenResponse.RefreshToken))
            {
              claims.Add(new Claim("refresh_token", tokenResponse.RefreshToken));
            }

            n.AuthenticationTicket.Identity.AddClaims(claims);

            return;
          },
          RedirectToIdentityProvider = n =>
          {
            // If signing out, add the id_token_hint
            if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.Logout)
            {
              var idTokenClaim = n.OwinContext.Authentication.User.FindFirst("id_token");
              if (idTokenClaim != null)
              {
                n.ProtocolMessage.IdTokenHint = idTokenClaim.Value;
              }
            }

            return Task.CompletedTask;
          }
        },
      });
    }
  }
}


Add an a new MVC 5 empty controller inside of Controllers folder. You can name it AccountController and paste the following code inside of it:

using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using System.Web;
using System.Web.Mvc;

namespace OktaAspNetMvcAngular.Controllers
{
  public class AccountController : Controller
  {
    public ActionResult Login()
    {
      if (!HttpContext.User.Identity.IsAuthenticated)
      {
        HttpContext.GetOwinContext().Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType);
        return new HttpUnauthorizedResult();
      }

      return RedirectToAction("Index", "Home");
    }

    [HttpPost]
    public ActionResult Logout()
    {
      if (HttpContext.User.Identity.IsAuthenticated)
      {
        HttpContext.GetOwinContext().Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType, OpenIdConnectAuthenticationDefaults.AuthenticationType);
      }

      return RedirectToAction("Index", "Home");
    }

    public ActionResult PostLogout()
    {
      return RedirectToAction("Index", "Home");
    }
  }
}


Add Login Section to Layout

Inside of Views/Shared folder create a new partial view named _LoginPartial and paste the following code inside:

@if (Context.User.Identity.IsAuthenticated)
{
  <ul class="nav navbar-nav navbar-right">
    <li>
      <p class="navbar-text">Hello, <b>@Context.User.Identity.Name</b></p>
    </li>
    <li>
      <a onclick="document.getElementById('logout_form').submit();" style="cursor: pointer;">Log out</a>
    </li>
  </ul>
  <form action="/Account/Logout" method="post" id="logout_form"></form>
}
else
{
  <ul class="nav navbar-nav navbar-right">
    <li>@Html.ActionLink("Log in", "Login", "Account")</li>
  </ul>
}


Set Up Your ASP.NET API Endpoints

You will use the controller as your endpoint source for the API. Add a new Web API controller namedJoggingRecordsController.cs class inside of your Controllers folder and paste the following code:

using OktaAspNetMvcAngular.Data;
using OktaAspNetMvcAngular.Models;

using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;

namespace OktaAspNetMvcAngular.Controllers
{
  public class JoggingRecordsController : ApiController
  {
    private ApplicationDbContext db = new ApplicationDbContext();

    // GET: api/JoggingRecords
    public IQueryable<JoggingRecord> GetJoggingRecords() => db.JoggingRecords;

    // GET: api/JoggingRecords/5
    [ResponseType(typeof(JoggingRecord))]
    public async Task<IHttpActionResult> GetJoggingRecord(int id)
    {
      JoggingRecord joggingRecord = await db.JoggingRecords.FindAsync(id);
      if (joggingRecord == null)
      {
        return NotFound();
      }

      return Ok(joggingRecord);
    }
  }
}


The code above adds two endpoints. The first one will fetch all JoggingRecords from the database. In your applications, you will probably want some kind of paging and filtering. The second endpoint will fetch individual JoggingRecords instances based on the id parameter that the client will pass to the API. That parameter will match the Id in JoggingRecords table in the database.

Set a Default Formatter for ASP.NET Web API 2

Unfortunately, ASP.NET Web API 2 is set to use XML as default formatter. Remove it and make sure JSON formatter is the default one. Add the following code at the end of the Register() method inside of WebApiConfig.cs file:

// Set JSON formatter as default one and remove XmlFormatter

var jsonFormatter = config.Formatters.JsonFormatter;
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Formatters.Remove(config.Formatters.XmlFormatter);
jsonFormatter.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;


You’ll also need to add the following using statement for the JSON serializer to the file:

using Newtonsoft.Json.Serialization;


You will also want to specify the port for your ASP.NET application. You need to know the exact address so you can communicate with the API from your Angular application. To do so, right click on the project in the solution explorer and click properties. In the main properties window, choose Web from the left-hand menu and set the Project Url property to http://localhost:8080.

Set Up the Angular Application for ASP.NET MVC

Since you will let your ASP.NET MVC application handle routing you can remove the app-routing.module.ts file and its references in the AppModule. Your app.module.ts file should look like this:

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

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

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


After that is done, delete the code from app.component.html.

You also need to make sure that the Angular CLI outputs files to the appropriate folder. Inside of your Angular folder open angular.json file and change the outputPath setting:

"outputPath": "../Bundles/AngularOutput",


In the ASP.NET MVC application, you will add a new JS and CSS bundle for Angular. Locate the BundleConfig.cs file inside of App_Start folder and at the end of the RegisterBundles function add the following code:

// Angular bundles
bundles.Add(new ScriptBundle("~/bundles/Angular")
  .Include(
    "~/bundles/AngularOutput/inline.*",
    "~/bundles/AngularOutput/polyfills.*",
    "~/bundles/AngularOutput/scripts.*",
    "~/bundles/AngularOutput/vendor.*",
    "~/bundles/AngularOutput/runtime.*",
    "~/bundles/AngularOutput/main.*"));

bundles.Add(new StyleBundle("~/Content/Angular")
  .Include("~/bundles/AngularOutput/styles.*"));


For this to work, you need to make use of these bundles inside of your views. You should first create a new MVC view for your Angular application. Create a new folder inside of Views folder called AngularData and inside of it create new Index.cshtml file:

@{
  ViewBag.Title = "Index";
}

@Styles.Render("~/Content/Angular")

<app-root>test</app-root>

@Scripts.Render("~/bundles/Angular")


The code above will actually render the JS bundle that our angular application produces. Angular will find the tag and render the App component and everything inside of it.

To access this view, you need to create a matching controller. Inside of Controllers folder create a new MVC 5 controller named AngularDataController:

using System.Web.Mvc;

namespace OktaAspNetMvcAngular.Controllers
{
  public class AngularDataController : Controller
  {
    public ActionResult Index()
    {
      return View();
    }
  }
}


You should also update the layout file so that you can access the Angular application from the menu bar. Locate the _Layout.cshtml file inside of Views/Shared folder. Make sure your navbar looks like this:

<ul class="nav navbar-nav">
  <li>@Html.ActionLink("Home", "Index", "Home")</li>
  <li>@Html.ActionLink("Angular", "Index", "AngularData")</li>
  <li>@Html.ActionLink("About", "About", "Home")</li>
  <li>@`Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>


To have the Angular application outputting the content, navigate inside of the Angular folder and open your favorite terminal. Enter the following command:

ng build --extractCss --watch


The command above will make sure that new bundle is produced whenever you change any code that is part of the Angular codebase, and it will also extract CSS from global styles into CSS files instead of JS ones.

Create a Model and API Service for Your Angular Application

Your app contains only one root module, AppModule, and one component AppComponent. Since the application that you will be making here is a small one you will not create additional modules. Once the application grows and gets more complicated, you should introduce new modules, shared modules to organize your code better. The application itself will only show some records from the API. However, since your Angular application is interacting with the server, you should create a separate Angular service for this purpose.

You can also create a TypeScript model for the JoggingRecord. First create a shared folder inside the app folder, which is part of the Angular application that gets created by the Angular CLI.

Inside of the shared folder create a new file — JoggingRecord.ts:

export default class JoggingRecord {
  id: number;
  distance: number;
  description: string;
  createdAt: string;
}


The class above will allow you to have a strongly typed model for the JoggingRecord inside of your Angular application.

You can now create the API service inside of the shared folder. Name the file api.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

import JoggingRecord from './JoggingRecord';

@Injectable()
export default class ApiService {
  public API = 'http://localhost:8080/api';
  public JOGGING_RECORDS_ENDPOINT = `${this.API}/joggingrecords`;

  constructor(private http: HttpClient) { }

  getAll(): Observable<Array<JoggingRecord>> {
    return this.http.get<Array<JoggingRecord>>(this.JOGGING_RECORDS_ENDPOINT);
  }
}


The ApiService class is the bridge between our Angular application and our Web API endpoints. You need it to fetch the data from our server.

Add the service to the App module by updating the providers array inside of app.module.ts file. You also need to import the HttpClientModule. Your app.module.ts file should end up looking like this:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';
import ApiService from '../shared/api.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    HttpClientModule,
    BrowserModule,
  ],
  providers: [ApiService],
  bootstrap: [AppComponent]
})
export class AppModule { }


Fetch Data from the ASP.NET API Endpoint

Update the app.component.ts file with the following content:

import { Component, OnInit } from '@angular/core';

import JoggingRecord from '../shared/JoggingRecord';
import ApiService from '../shared/api.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit  {
  joggingRecords: Array<JoggingRecord>;

  constructor(private apiService: ApiService) {
  }

  ngOnInit() {
    this.apiService.getAll().subscribe(data => {
      this.joggingRecords = data;
    });
  }
}


The code above will subscribe will assign the data that ApiService fetches from server to the joggingRecords property.

You also need to update this component’s template (app.component.html):

<div style="text-align:center">
  <h1>
    Jogging Records
  </h1>

  <span *ngFor="let record of joggingRecords">
    {{record.description}} - {{record.distance}}
    <br />
  </span>
</div>


Test Out Your ASP.NET and Angular Application

Since you already have the Angular CLI outputting the code changes for your Angular application in the Bundles/AngularOutput folder, and your MVC application is making use of that folder you can simply start the MVC application and preview Angular app inside of it.

From your Visual Studio use CTRL+F5 to start the application your browser should open and you should see the following screen:

Clicking on the Angular link in the menu will actually render the MVC view for the Angular application and from that point it’s Angular who is in charge of rendering. The Angular page should look like this:

If you open the Dev Tools on your editor you should see that the Angular application actually hits the ASP.NET API:

Learn More

Angular 7 (formerly Angular 2) - The Complete Guide

Learn and Understand AngularJS

Angular Crash Course for Busy Developers

The Complete Angular Course: Beginner to Advanced

Angular (Angular 2+) & NodeJS - The MEAN Stack Guide

Become a JavaScript developer - Learn (React, Node,Angular)

Angular (Full App) with Angular Material, Angularfire & NgRx

The Web Developer Bootcamp

The Complete ASP.NET MVC 5 Course

Build a Real-world App with ASP.NET Core and Angular 2 (4+)

ASP NET Core (ASP.NET 5),MVC 6,C#,Angular2 & EF Crash Course