DotNetCurry Logo

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

Posted by: Mark Kendall , on 5/30/2015, in Category ASP.NET MVC
Views: 38121
Abstract: In this article we will continue to incorporate AngularJS into an ASP.NET MVC Project.

So far in the other 2 articles Look, up in the sky, its ASP.NET MVC 5 shining down on your Enterprise development and Using AngularJS in your ASP.NET MVC Projects - Part 2 we looked at how to incorporate AngularJS into an ASP.NET MVC Project, and looked at one of many ways you can use both the AngularJS and MVC Routing systems side-by-side. In this article we will continue to look at both the AngularJS code and MVC code.

I have added many lines of code for you to use and change to fit your individual requirements. For example, I used a sample from the AngularJS site and re-coded it to run in the MVC framework. Download the source code as in this article, I will be only explaining the important bits.

After installation of the site on your local machine, check out this page by clicking “Check Angular” - and you can walk through the code to see it in action.

 

In addition, as I promised- the entire site is available for download.

angular-sample

Getting Started with AngularJS and the MVC Framework as Team

As we discussed, AngularJS and the MVC Framework work very well together and it is important to look at the right coding technique for the job.

That is, you probably don’t want to use AngularJS for every page. If you don’t need a dynamic structured page, for example in the case of an AboutUs page, you can use the MVC framework and the scaffolding system to get you up and running. Don’t let anyone tell you it has to be one or the other. That is simply wrong. As I said, they work together very well once you get used to it.

Let’s look at some more code!

On this page- I put together a tabbing system for you that I also re-coded from the Official AngularJS site that demonstrates a nice user interface that you can use in your apps with some simple angular commands to boot.

I am not going to take all the fun out of it and go through over every line of code, I will let you do that as I have already done the hard part! Make sure you read my previous articles. This article also assumes you have knowledge of AngularJS concepts and how it uses MVC. If you are absolutely new to these concepts, check this getting started guide on AngularJS.

angular-mvc

 

The Angular code to call ASP.NET Web API

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

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

        //Function to Read All Employees
        var getArtists = function () {
            return $http.get("api/ArtistsAPI/");
        };

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

This is standard AngularJS Code that uses dependency injection (($http, $q, $log) and is well-structured JavaScript code. If you are not familiar with this code, you would do well by studying it and becoming as familiar as you can with JavaScript- because in my opinion, professional developers will need to become almost experts at JavaScript over the next 10 years to stay relevant in the market!

All of the JavaScript files are located in the MyScripts folder and you can take a look at Modules, Controllers, Services and more. Remember, it’s just our old friend MVC and only on the client side, so you should be familiar with a lot of patterns used in the JavaScript. If you don’t know the particulars, just spend some time reviewing the patterns in detail.

servicesjs

Basic Security was added (out-of-box) so you can authenticate and authorize users:

authenticate

 

As you know you add an [Authorize] attribute to your MVC controllers if you want to secure your pages as shown below:

[Authorize]
    public class EmployeeInfoController : Controller
    {
        // GET: EmployeeInfo

        public ActionResult Index()
        {
            return View();
        }

Here is the controller for the ShowArtistsController

app.controller('ShowArtistsController', function ($scope, $location, artistsService, ShareData) {

    loadRecords();

    //Function to Load all Artists Records.   
    function loadRecords() {
        var promiseGetArtists = artistsService.getArtists();

        promiseGetArtists.then(function (pl) { $scope.Artists = pl.data },
              function (errorPl) {
                  $scope.error = 'failure loading Artists', errorPl;
              });
    }

    $scope.addArtist= function () {
        $location.path("/addartist");
    }

    $scope.editArtist = function (ArtistNo) {
        ShareData.value = ArtistNo;
        $location.path("/editartist");
    }

    $scope.deleteArtist = function (ArtistNo) {
        ShareData.value = ArtistNo;
        $location.path("/deleteartist");
    }
});

The controllers on the MVC Framework remain the same and when the page is AngularJS they become even simpler with a few lines of code in the ActionResult methods:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

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

        public ActionResult About()
        {
            ViewBag.Message = "TendollarTraining.com";

            return View();
        }


        public ActionResult Contact()
        {
            ViewBag.Message = "TendollarTraining.com";

            return View();
        }
    }
}

Debugging the code
There are a couple of things you will want to keep in mind when it comes to debugging:

  • Use IE if you want to use Visual Studio to set break points on both the client and server code
  • Use Google chrome if you want to use the developer tools, console and maybe the network tools
  • If you are using the .min versions of JavaScript, you won’t be able to walk through your code- so don’t minify until you’re ready to go to production

Conclusions
In the series of articles, we looked out how you might use AngularJS and the MVC Framework to produce modern websites for your companies and clients, and we were cautious not to alienate the folks who still like to code with ASP.net WebForms- as it is a lifestyle choice in my opinion.

But if you have decided to move in the AngularJS MVC framework direction, I hope you found some things that will make your lives easier.

At the end of the day, it is important to remember that you need to pick the right tools for the job, as it not always going to be one way or the other- so do the right thing for your customers and clients and choose this approach if it fits the requirements of the job.

I have provided the entire code base so that you can start from a good reference point and you can see it here live to get an idea of the possibilities:
http://mvcangdotcurry.azurewebsites.net/

Happy coding!

Download the entire source code of this article (Github)

Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+
Further Reading - Articles You May Like!
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!