Using AngularJS in your ASP.NET MVC Projects - Part 2

Posted by: Mark Kendall , on 4/5/2015, in Category ASP.NET MVC
Views: 166554
Abstract: Incorporate AngularJS Framework into your ASP.NET MVC projects and seamlessly use both the MVC routing system along-side the AngularJS routing system. This is part 2 of a series of articles on ASP.NET MVC to make you more productive on the MVC Framework.

In our web development, we are always looking for the best approach to solve our business problems, and in the first article in this series Look, up in the sky, its ASP.NET MVC 5 shining down on your Enterprise development we looked at using the MVC framework as the best way of getting our projects on track. In this article, we will look at bringing in AngularJS into our MVC projects and look at the ways in which we can get these two superior frameworks to work side-by-side.

As most of you know, learning one framework is hard enough- let alone two, but I think it can be a manageable task if you keep the separation-of concerns (SoC) concepts clearly in your mind and more importantly to also remember that software development is more than click, click, and click. So let’s get started and have some fun with Angular JS and MVC 5.

 

Editorial Note: Separation of Concerns (decoupling) or SoC is a principle that promotes best practices for software architecture. A ‘concern’ can be considered as an aspect of software functionality. For eg: The UI can be a concern, the business logic can be another concern and so on. The idea is to make sure each concern has a single, well-defined purpose and to find a balanced way to separate these features and concepts into different modules. This ultimately reduces duplicate code and keeps the modules decoupled from each other, making our application maintainable and manageable. As a very basic example of SoC, think about HTML, CSS and JavaScript, where all these technologies have a well-defined purpose. HTML defines the content structure, CSS defines content presentation and JavaScript defines how the content interacts and behaves with the user. Check Mark and Todd’s previous article to learn how MVC realizes the SoC principle.

This article has been co-authored by Mark Kendall and Todd Crenshaw.

Getting Started with AngularJS

This article assumes you have a very basic knowledge of AngularJS concepts and how it uses MVC. If you are absolutely new to these concepts, check this getting started guide on AngularJS. Once you are through with the concepts, you can also check our new video course that demonstrates how to incorporate AngularJS with MVC. Check Intro To AngularJS - A Must For ASP.Net & MVC 5 Developers (10% discount applied).

Let’s get started by looking at how to get a basic AngularJS page up and running. Here is the code from Home.html in the project download files. This file will show you the basics to get the Framework installed and running inside the project file. Here are the basic steps to get the file to run inside your project:

  • Load the scripts <script src="Scripts/angular.min.js"></script>
  • Set the Directives ng-app="ngArtistDemo">
  • Create the Module
  • Create the controllers
  • Create the services
  • Read the output Artist: {{artist.FirstName}}
<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml" ng-app="ngArtistDemo">
<head>
    <script src="Scripts/angular.min.js"></script>
    <script src="Scripts/angular-route.min.js"></script>
    <script src="Scripts/app.js"></script>
    <script src="Services/ArtistService.js"></script>
    <title></title>
</head>

<body>
    <h1>Welcome to the Angular Portion of this Dotnetcurry Article!</h1>
    <div ng-controller="ngAppDemoController">
        I can add: {{a}} + {{b}} =  {{ a+b }}
    </div>

    <div ng-controller="ngAppDemoController">
        <div ng-repeat="artist in Artists">
            Artist: {{artist.FirstName}}
        </div>
 
    </div>

    <div ng-controller="TenDollarController1">
        Name: <input ng-model="name"><br />
        The value of A from the scope, {{a}}!
        The value of B from the scope, {{b}}!

        <p>
            TenDollarTraining.com - Making online education affordable for everyone. A Microsoft Partner with over 20+ years of teaching and development experience.
        </p>
    </div>

    <div ng-controller="TenDollarController2">
        Name: <input ng-model="name"><br />
        Hello, {{name}}!

        <p>
            TenDollarTraining.com - Making online education affordable for everyone. A Microsoft Partner with over 20+ years of teaching and development experience.
        </p>
    </div>
</body>

</html>

angular-result

*The above is the output of running the code from above.

Let’s look at the other components

The following is the code for creating a Module and can be found in app.js. A Module in AngularJS is like a container. It can contain different parts of your application like – Controllers, Services, Filters, and Directives etc. You can learn more about AngularJS modules over here.

var app = angular.module('ngArtistDemo', ['ngRoute'])
 .controller('ngAppDemoController',['$scope','artistsService',

 function ($scope, artistsService) {
    $scope.a = 1;
    $scope.b = 2;
    console.log("AngularJS is initialized and ready to go!");

    var artists = function (data) {
        $scope.Artists = data;
        //console.log($scope.Artists);
    };

    var errorDetails = function (serviceResp) {
        $scope.Error = "Something went wrong ??";
    };  

    artistsService.artists().then(artists, errorDetails);
   
 }])
 .controller('TenDollarController1', ['$scope',
 function ($scope) {
    $scope.a = 1;
    $scope.b = 2;
}])
.controller('TenDollarController2', ['$scope',
function ($scope) {
    $scope.name = "World";
}]);

app.config(function ($routeProvider) {
    $routeProvider
        .when("/Home", {
            templateUrl: "/Home.html",
            controller: "ngAppDemoController"
        })
    .otherwise({ redirectTo: "/Home" })
});

And now let’s look at the Service to retrieve the Artists Data

Following is the code for creating the module and can be found in the ArtistService.js. Learn more about AngularJS Services over here.

(function () {
    var artistsService = function ($http, $q, $log) {
        var cachedArtist;

        var artists = function () {
            return $http.get("http://localhost:11111/api/ArtistsAPI")
                        .then(function (serviceResp) {
                            return serviceResp.data;
                        });
        };       

        return {
            artists: artists,
           
        };
    };
    var module = angular.module("ngArtistDemo");
    module.factory("artistsService", ["$http", "$q", "$log", artistsService]);
}());

What have we just done?
Well folks this is the AngularJS way and you need to get your heads around how to use the constructs of a JavaScript Framework. It takes a little getting used to, but once you get the hang of it, you can move fairly quickly through the process of building solutions to your business problems.

 

The nice thing is that we have the same components as we have in MVC- yes, the Model. View and the Controller- but just done a little differently. It is said that the angular way is more like a MVVM design pattern- which simply means that the controller does more of the processing making the model more accessible to the view- but essentially the same.
This article won’t focus on line-by-line analysis of the above code, as you can do the analysis yourselves once you have understood the basics. As already mentioned, there are many good articles on dotnetcurry.com that you can use to start becoming an expert at Angular and call the asp.net webapi for the model data. This is where I spend a lot of my time learning from others.

References: Project Tracking Website using AngularJS and ASP.NET Web API & Single Page CRUD Application (SPA) using ASP.NET Web API, MVC and Angular.js

How do we get both AngularJS and ASP.NET MVC working together in the same project?

One of the things most of the articles on these two frameworks are lacking is the interaction of the two frameworks when you do get pretty good at both of them.

In particular, both frameworks have their own routing systems and don’t always play well together when it comes to switching back and forth from the routing systems and securing the application through Authentication and Authorization- so let’s talk about that now.

One of the problems with AngularJS routing system is that once you switch over to your SPA (Single Page Application), there is seemingly no way to get back to serving up regular MVC pages
and everything seems to run amuck- and the user ends up with a poor user experience and everyone is mad- including your boss!!
The magic is in the otherwise clause of the app.config - catch a route that you didn’t define and you can reroute back to the MVC routing system and you are off and running again. You are able to logoff, serve MVC pages etc.

The important part

$routeProvider.otherwise(
                        {
                           
                            controller: "MainCtrl",
                            template: "<div></div>"
                        });
    $locationProvider.html5Mode(true).hashPrefix('!')
}])
.controller('MainCtrl',[  '$rootScope','$window',
function($rootScope,$window){
  $rootScope.$on("$routeChangeStart", function (event, next, current) {
      if (next && !next.$$route) {
          event.preventDefault(); // Stops the ngRoute to proceed with all the history state logic
          // We have to do it async so that the route callback 
          // can be cleanly completed first, so $timeout works too
          $rootScope.$evalAsync(function() {
              next.redirectTo = 'http://localhost:11111/'
              $window.location.href = next.redirectTo;
          });
      }
  });
}

Complete file

var app = angular.module("ArtistsModule", ["ngRoute"]);

    app.config(['$routeProvider','$locationProvider', function ($routeProvider,$locationProvider) {

     //Angular Pages
        $routeProvider.when('/showartists',
                            {
                                templateUrl: 'Artists/ShowArtists',
                                controller: 'ShowArtistsController'
                            });

        $routeProvider.when('/Home',
                          {
                              templateUrl: 'Home/Index',
                              
                          });
     //MVC Pages


        $routeProvider.when('/Home/Index',
                        {
                            templateUrl: 'Home/Index',

                        });

        $routeProvider.when('/Home/Logoff',
                         {
                             templateUrl: 'Home/Logoff',

                         });
        $routeProvider.when('/Home/Contact',
                       {
                           templateUrl: 'Home/Contact',

                       });
        $routeProvider.when('/Home/About',
                      {
                          templateUrl: 'Home/About',

                      });


        $routeProvider.when('/Account/Register',
                     {
                         templateUrl: 'Account/Register',

                     });
        $routeProvider.when('/Account/Login',
                   {
                       templateUrl: 'Account/Login',

                   });

        $routeProvider.otherwise(
                            {
                               
                                controller: "MainCtrl",
                                template: "<div></div>"
                            });
        $locationProvider.html5Mode(true).hashPrefix('!')
    }])
    .controller('MainCtrl',[  '$rootScope','$window',
  function($rootScope,$window){
      $rootScope.$on("$routeChangeStart", function (event, next, current) {
          if (next && !next.$$route) {
              event.preventDefault(); // Stops the ngRoute to proceed with all the history state logic
              // We have to do it async so that the route callback 
              // can be cleanly completed first, so $timeout works too
              $rootScope.$evalAsync(function() {
                  next.redirectTo = 'http://localhost:11111/'
                  $window.location.href = next.redirectTo;
              });
          }
      });
  }
]);

Output

When I click on admin from the site above, I am asked to login and am then routed to a login page with the normal MVC routing. After successful login. I am routed to my SPA
and I am in AngularJS Heaven as you see below:

angular

When I click home, I am routed back to MVC routing and I can go about my business- including logging off and launching MVC parts of the application- Happiness all around!!

angular1

Conclusion

In this article we have covered the basics of getting AngularJS up and running inside an MVC project. You now have all the building blocks to use both the MVC framework and AngularJS to solve your business problems. In the next and last article in the series, we will bring it all together and produce a full web site that demonstrates the power of the MVC/AngularJS model of web development. In the meantime, if you need to get up to speed on AngularJS and MVC, use the reference articles to get a good jumpstart on the learning process.

Yes there is still a lot to learn when it comes to getting the best out of MVC and AngularJS but we are on the right track. The good news is that these are modern frameworks and if you master them you will be on the road to becoming and awesome programmer solving business problems for your employers and clients, and making the most of your career!

Reach out to us using the email given in my profile at the bottom.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Mark Kendall is a Software Engineer working in the Oil Industry in Dallas,Texas. He has been a programmer/developer for past 15 years specializing in .NET/C# development. Currently, he is a Sharepoint/Silverlight developer specializing in BCS Services. He has published a book on Dotnetnuke, and written several articles on many .net subjects. Apart from his passion for making money writing software to improve business, Mark enjoys ranting-and-raving about current events and taking long runs on the beach. He blogs at kendallsoft and can be reached at Kendallsoft[attherate]hotmail[dot]com


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by shalamos on Monday, April 6, 2015 6:18 AM
Thank you Mark Kendall and Todd Crenshaw. This article answered some questions I had in mind. I hope you publish part 3 soon.
Comment posted by cvcff on Monday, May 18, 2015 7:29 AM
vfgfffg