Angular JS is (yet another) client side MVC framework in JavaScript that has caught the imagination of the web world in recent times. It was created by a group of developers at Google when they realized that their project (Feedback) had become too unwieldy and needed a cleanup. The three weeks effort at that cleanup lay seed to what is now known as AngularJS. Of course AngularJS was thrown open to community and since then has garnered a vibrant community and a boat load of features.
Among things that make AngularJS popular is its focus on testability by having principles of Dependency Injection and Inversion of control built into the framework.
Angular JS with vanilla ASP.NET MVC
Today we will look at AngularJS in a plain vanilla ASP.NET MVC app. We’ll start with an empty project and go ground up. We will start with basic data binding and retrieving of data, then walk through other core Angular features like directives and routing.
2nd part of this article - Posting Data & AngularJS Custom Directives in an ASP.NET MVC application
3rd and final part - Defining AngularJS Routing in an ASP.NET MVC application
This article is published from the DotNetCurry .NET Magazine – A Free High Quality Digital Magazine for .NET professionals published once every two months. Subscribe to this eMagazine for Free and get access to hundreds of free tutorials from experts.
Basics of Databinding
For this article, we could have done the entire code walkthrough without any server side component and some hardcoded client side data, but that’s too far away from the real world. So we’ll get some data from the ethereal data stream, that is Twitter, and display it in our Application demonstrating the concept of model binding and directives in AngularJS.
To connect to Twitter, we’ll use the excellent Linq2Twitter library on the server side. Once we have logged in, we’ll retrieve and display data using AngularJS. So before we get AngularJS, lets scaffold an ASP.NET MVC app and hook it up with LinqToTwitter. As with all Twitter apps, we have to get a CustomerKey and a CustomerSecret from dev.twitter.com.
Scaffolding the ASP.NET MVC App
1. We create a MVC4 project with the Empty template as we want to get started with the bare bones today.
2. We add LinqToTwitter from Nuget
PM> install-package linqtotwitter
3. We install Twitter Bootstrap CSS and JavaScript files using the following command
PM> install-package Twitter.Bootstrap
4. We add an Empty HomeController in the Controllers folder. The Index action method calls the Authorization function and if the current user is not Authorized, it redirects to Twitter’s Authorization page. Once Authorized, it navigates back to Index page.
Very briefly, the ConsumerKey and the ConsumerSecret that we got while creating Twitter app is in the AppSettings. These two along with the OAuth token returned by Twitter, complete the Authorization part.
Note: We have not taken any measure to hide our Auth token once it returns from the Server. In a production application, make sure not to leave it unprotected.
public class HomeController : Controller
{
private IOAuthCredentials credentials = new SessionStateCredentials();
private MvcAuthorizer auth;
private TwitterContext twitterCtx;
public ActionResult Index()
{
var unAuthorized = Authorize();
if (unAuthorized == null)
{
return View("Index");
}
else
{
return unAuthorized;
}
}
private ActionResult Authorize()
{
if (credentials.ConsumerKey == null || credentials.ConsumerSecret == null)
{
credentials.ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"];
credentials.ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"];
}
auth = new MvcAuthorizer
{
Credentials = credentials
};
auth.CompleteAuthorization(Request.Url);
if (!auth.IsAuthorized)
{
Uri specialUri = new Uri(Request.Url.ToString());
return auth.BeginAuthorization(specialUri);
}
ViewBag.User = auth.Credentials.ScreenName;
return null;
}
...
}
MVC5 Notes: Due to changes in ASP.NET Security Policies, DotNetOpenAuth (used internally by Linq2Twitter) breaks, so we have to use a workaround as defined here. The code accompanying this article incorporates this workaround. However since this is not related to the core topic, I have skipped the details.
5. Finally we add a method that returns a JsonResult containing list of Latest Tweets from the logged in user
[HttpGet]
public JsonResult GetTweets()
{
Authorize();
string screenName = ViewBag.User;
IEnumerable< TweetViewModel > friendTweets = new List< TweetViewModel >();
if (string.IsNullOrEmpty(screenName))
{
return Json(friendTweets, JsonRequestBehavior.AllowGet);
}
twitterCtx = new TwitterContext(auth);
friendTweets =
(from tweet in twitterCtx.Status
where tweet.Type == StatusType.Home &&
tweet.ScreenName == screenName &&
tweet.IncludeEntities == true
select new TweetViewModel
{
ImageUrl = tweet.User.ProfileImageUrl,
ScreenName = tweet.User.Identifier.ScreenName,
MediaUrl = GetTweetMediaUrl(tweet),
Tweet = tweet.Text
})
.ToList();
return Json(friendTweets, JsonRequestBehavior.AllowGet);
}
private string GetTweetMediaUrl(Status status)
{
if (status.Entities != null && status.Entities.MediaEntities.Count > 0)
{
return status.Entities.MediaEntities[0].MediaUrlHttps;
}
return "";
}
6. The ViewModel used to encapsulate a Tweet is as follows
public class TweetViewModel
{
public string ImageUrl { get; set; }
public string ScreenName { get; set; }
public string MediaUrl { get; set; }
public string Tweet { get; set; }
}
7. Next we setup the View skeleton using BootStrap (you need to do this if you are using VS2012 or older). VS2013 and MVC5 project template will automatically setup the _Layout to use BootStrap):
a. Add _ViewStart.cshtml in the Views folder. It’s content is as follows
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
b. Add Views\Shared\_Layout.cshtml folder that will serve as our Master Page
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Hello AngularJS</title>
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="navbar navbar-inverse">
<div class="navbar-inner">
<div class="brand">
@ViewBag.Title
</div>
@if (ViewBag.User != null)
{
<div class="button-group pull-right">
<div class="btn">
<i class="icon-user"></i>
@ViewBag.User
</div>
</div>
}
</div>
</div>
<div class="container-fluid">
<div class="row-fluid">
@RenderBody()
</div>
</div>
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
</body>
</html>
c. Finally we add Index.cshtml which only has a Title for now
@{
ViewBag.Title = "Hello AngularJS";
}
d. If we run the application at this point, it will ask to Authorize our app with Twitter, and once authorized, we’ll be redirected to the home page as follows

That completes our ground work and we are ready to dive into AngularJS now.
The Angular App
First point of difference from libraries like KnockoutJS is that Angular needs an ng-app attribute to be declared, wherever we want the Scope of Angular to start. We will add it in our Index.cshtml by adding a div as follows.
<div ng-app>
<!-- More Goodness Coming -->
</div>
The AngularJS Client Side Controller and ViewModel
We will add a hello-angular.js in the Scripts folder. We start off with a Controller that is defined as follows:
var indexController = function ($scope)
{
}
In Angular, the indexController object is regarded as Controller simply if someone pulls in the ($scope) parameters.
What is $scope?
$scope is the client side version of ViewBag as we know from MVC. It is used for sharing data between the Angular Controller and the View.
How do we use $scope?
1. As we mentioned above, we use Scope as a ViewBag, so to start off with, we’ll add a Json array in it.
var indexController = function ($scope){ $scope.tweets = [ { screenName: "Sumit", tweetText: "Test 1" }, { screenName: "Sumit", tweetText: "Test 2" }];}
Using Scope and Data Binding in AngularJS
2. Next we go back to Index.cshtml and add the following markup.
<!-- More Goodness Coming -->
<div ng-controller="indexController">
<ul>
<li ng-repeat="item in tweets">
{{item.screenName}}, {{item.tweetText}}
</li>
</ul>
</div>
Introducing Angular Directives
There is a lot of stuff going on here.
a. In the outermost div, we have specified the directive ng-controller=”indexController”. This specifies what is the scope of the $scope object.
b. Note the ul doesn’t have anything special, so data binding to collections is by default container less.
c. The li element finally defines the ng-repeat directive and sets it to tweets (as defined in $scope earlier). Note the syntax is like C#’s foreach.
d. Finally we have the {{ … }} handlebar syntax to define the placeholders.
Those who are familiar with KO’s data binding will note how Angular doesn’t use data- attributes, rather it uses AngularJS Specific attributes that it modifies at runtime. If we run this app now, we’ll see the following:

We can see how the DOM has been manipulated at runtime to get the output.
Just to recap, the $scope that was passed into the controller was actually instantiated and passed by Angular. Those familiar with constructor injection will realize that Angular actually injected the $scope without us having to worry about it. This is the uniqueness and strength of Angular.
The Pluralizer Directive
We have been using the term Directives without explaining it so far. Directives in AngularJS are special keywords that have built in functionality. They can apply to elements attributes, classes or comments. We put in a ‘Pluralizer’ directive to see the total number of tweets.
In the view, we add the following markup inside the scope of the ng-controller
<h3>
<ng-pluralize count="tweets.length" when="newTweets"></ng-pluralize>
</h3>
The ng-pluralize directive can be read as ‘check for the count in tweets.length and based on it, evaluate the switch case in the newTweets function.’ Actually newTweets is an object in our indexController that we define as follows:
$scope.newTweets = {
0: "No new Tweets",
other: "{} new Tweets"
}
So now our ng-pluralize delegate reads like – “check for the count in tweets.length and if there are no tweets put the text “No new Tweets” else put the text ‘n new Tweets’ where n is the count”.
If we run the application as is, we’ll get the following

Nice. Now let’s move on and see how we can get data from the Server.
Promises and Fetching Data from Server
Angular makes it really easy to get data from the server using AJAX. We’ll update our client controller (hello-angular.js) as follows:
var indexController = function ($scope, $http)
{
var resultPromise = $http.get("/Home/GetTweets");
resultPromise.success(function (data)
{
$scope.tweets = data;
});
$scope.newTweets = {
0: "No new Tweets",
other: "{} new Tweets"
}
}
Notice the additional parameter $http, getting injected into the controller. This is a wrapper for http functions as we can guess. We will use this to retrieve the Promise return by the $http.get(…) call. A promise is like a delegate or callback used when doing Async AJAX calls. Note we are calling the GetTweets method on our server controller. Once the Promise (delegate) completes successfully, we get the actual JSON data from the server.
Let’s update the Index.cshtml to create a nice list of the Tweets
<!-- More Goodness Coming -->
<div ng-controller="indexController">
<h3>
<ng-pluralize count="tweets.length" when="newTweets"></ng-pluralize>
</h3>
<table class="table table-striped">
<tr ng-repeat="item in tweets">
<td>
<img src="{{item.ImageUrl}}" />
</td>
<td>
<strong>{{item.ScreenName}}</strong> <br />
{{item.Tweet}}
</td>
</tr>
</table>
</div>
There are a couple of new things to note
a. We have moved the ng-repeat from the li to the tr tag.
b. We have added an img element and notice how the src is bound in-place to the ImageUrl property in our ViewMode.
Well with that, we are all set. Run the Application and a view like the following comes up!

Pretty neat eh! For devs familiar with data-binding in any form (no pun intended), be it WebForms, WPF, Silverlight etc. Angular’s binding philosophies match closely except for the fact that Angular’s magic happens on the browser.
Modules and Services in AngularJS
Modules in AngularJS
Modules are a way in AngularJS to organize and structure code. It is in a way, similar to Namespaces in C#, but Modules are more than passive naming constructs.
Declaring a Module
The syntax for creating a Module is as follows:

Notice the empty array parameter. This is actually an array of resources (we’ll see what are resources shortly), however if you don’t have any resources to pass, you need to pass an empty array. Missing out on the empty array may result in ‘undesired’ results.
As mentioned, Modules are like namespaces, so to add your Controller to the Module instead of having the controller floating around in JavaScript like in our previous example, we update the Controller to be a function in our module as follows:
var ngTwitter = angular.module("ngTwitter", []);
ngTwitter.controller("TimelineController", function ($scope, $http) {
var resultPromise = $http.get("/Home/GetTweets");
resultPromise.success(function (data) {
$scope.tweets = data;
});
$scope.newTweets = {
0: "No new Tweets",
other: "{} new Tweets"
}
});
Note for better context, I’ve renamed the controller from IndexController to TimelineController because it is essentially showing Twitter’s Timeline.
Using the Modules in your View
Now that the Module has been declared, our Controller is no longer ‘visible’ to the Angular directly. So if we run the application as is, we’ll get errors on our Developer Console saying the Controller was not found.
To hookup the Module, we need to specify it in the ng-app attribute. This tells Angular which module to use for a given section on our page.
Since we changed the name of the Controller, we go ahead and change that as well. Our updated markup is as follows:
<p style="background-color: #ffff00" ng-app="<font">"ngTwitter"</p>
>
<!-- More Goodness Coming -->
</p>
<p style="background-color: #ffff00" ng-controller=""<font">TimelineController</font>">
</p>
<h3 style="background-color: #ffff00" ng-controller=""<font">
<ng-pluralize when=""newTweets"" count=""tweets.length""></ng-pluralize>
</h3>
<p style="background-color: #ffff00" ng-controller=""<font">
</p>
<p style="background-color: #ffff00" ng-controller=""<font">
<table class=""table" table-striped"="table-striped"" unselectable="on">
<tbody>
<tr tweets"="tweets"" in="in" ng-repeat=""item">
<td>
<img src=""{{item.ImageUrl}}"" />
</td>
<td>
<strong>{{item.ScreenName}}</strong>
{{item.Tweet}}
</td>
</tr>
</tbody>
</table>
</p>
<p style="background-color: #ffff00" ng-controller=""<font"> </p>
If we run the app now, things should work fine.
Next we look at defining a service which is again, more of code restructuring than a new framework feature.
Your first AngularJS Service
Services in AngularJS are simply reusable bits of code aiming to help make your app linear and more testable.
Declaring a Service
You can create Services in Angular using either the factory method or the service method provided by Angular. The Factory method returns a simple object, whereas the Service method returns a function. To start off with, we’ll use the Factory method and declare our service as follows:
ngTwitter.factory("TwitterService", function ($http) {
return {
timeline : function()
{
return $http.get("/Home/GetTweets");
}
}
});
Notice that we have passed $http service into our TwitterService and Angular injects it for us at runtime.
Using a Service
To use it, we simply ‘ask’ for it in our Controller function and Angular injects it for us. Now instead of calling the $http service directly, we call our TwitterService and request for the timeline. This still returns a promise so we continue to use the success completion method to bind our tweets.
ngTwitter.controller("TimelineController", function ($scope, TwitterService) {
var resultPromise = TwitterService.timeline();
//var resultPromise = $http.get("/Home/GetTweets");
resultPromise.success(function (data) {
$scope.tweets = data;
});
$scope.newTweets = {
0: "No new Tweets",
other: "{} new Tweets"
}
});
Neat! Another bit of code restructuring making our code more granular as we go along.
The Angular $Resource Provider
The Angular Resource provider is a plugin that can be used to further abstract and modularize our code. But first up, the Resource provider is in a separate JavaScript file angular-resource.js. So we’ve to add a reference to it to our markup.

Using the $Resource Provider
Next we tell our Module that it needs to use the Resource provider. We do that by passing ngResource, the name of the provider, in the array or resources that we had left empty earlier.
var ngTwitter = angular.module("ngTwitter", ['ngResource']);
Next we update our service to use the resource provider instead of $http directly.
ngTwitter.factory("TwitterService", function ($resource) {
return {
timeline: $resource("/Home/GetTweets")
};
});
This change may confuse you. We were using $http.get(…) and now we are directly using $resource(…). How does that work?
Well, from the Description provided in the documentation of AngularJS - A factory which creates a resource object that lets you interact with RESTful server-side data sources.The returned resource object has action methods which provide high-level behaviors without the need to interact with the low level $http service.
So basically it is a helper around the $http service and internally provides Get, Save, Query, Delete functions.
We’ll use the query method in our controller to get our timeline back. Notice now we no longer have to wait for a promise to return. The trick here is Angular returns an empty promise when the query is fired, and when it returns, it internally updates the original promise with array of objects that were returned. Since we are using data binding, the UI updates itself appropriately.
ngTwitter.controller("TimelineController", function ($scope, TwitterService) {
$scope.tweets = TwitterService.timeline().query({}, isArray = true);
$scope.newTweets = {
0: "No new Tweets",
other: "{} new Tweets"
}
});
Run the Application and we see a familiar response with a set of 20 latest tweets from our timeline.
That wraps up our code re-structuring and brings Part-1 of the Getting started with AngularJs in ASP.NET MVC to an end.
In the 2nd part of this article, - Posting Data & AngularJS Custom Directives in an ASP.NET MVC application, we will see the steps using the Resource provider to perform other actions like POSTing data to our server to send new Tweets. We also see how to use Custom AngularJS Directives, adding a Retweet functionality as well as Routing in AngularJS.
3rd and final part will demonstrate Defining AngularJS Routing in an ASP.NET MVC application
This article was published from the Free DNC magazine for .NET Developers . You can also download the entire source code of the app.
This article has been editorially reviewed by Suprotim Agarwal.
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!
Was this article worth reading? Share it with fellow developers too. Thanks!
Sumit is a .NET consultant and has been working on Microsoft Technologies since his college days. He edits, he codes and he manages content when at work. C# is his first love, but he is often seen flirting with Java and Objective C. You can follow him on twitter at @
sumitkm or email him at sumitkm [at] gmail