Tuesday, June 24, 2014

Creating an Empty ASP.NET Project Powered by AngularJS using Visual Studio

First of all, I always had trouble with JavaScript. Sometimes back I started using AngularJS and the way AngularJS implements MVC pattern kind of increased my interest towards JavaScript. Currently I am working in a Single Page Application(SPA) powered by AngularJS which communicates with the back end through ASP.NET Web API. I really am seeing the beauty of AngularJS these days.

So if you want to learn AngularJS, of course you need to know how to setup a AngularJS project in Visual Studio. There are couple of Visual Studio templates available like AngularJS SPA Template, which you can download and use with Visual Studio. But in this post, let’s see how you can create one from the scratch.

Let’s power up Visual Studio and create an Empty ASP.NET project (Please note I am using Visual Studio 2013).
image
ASP.NET Web Application
image
Empty Project
After creating the project, first let’s add AngularJS to the project using Nuget.
image
Adding AngularJS through Nuget
Alternatively, you can use Package Manage Console to install AngularJS. Once it gets installed, you can see a new folder named “Scripts” added to the project which contains all the AngularJS files needed to start the project off with.

Now inside my project, let’s create a folder named “App”. The “App” folder is going to be the one folder which will contain all our UI components. Inside “App” folder, let’s create two folders named “controllers” and “views”. “controllers” folder will contain all the AngularJS controllers and “views” folder will contain all the templates (html pages). All the templates will be rendered inside one html page. Let’s create that main html page named “Index.html” inside “App” folder.
image
Add new HTML page
Index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Sample AngularJS project using Visual Studio</title>
</head>
<body>
    
</body>
</html>
Let’s add a JavaScript file named “app.js” inside the “App” folder and let’s define AngularJS main module there.
image
App folder
app.js
var app = angular.module('myApp', ['ngRoute'])
.config(['$routeProvider', function ($routeProvider) {
    $routeProvider
      .when('/', {
          templateUrl: 'views/home.html',
          controller: 'homeController'
      })
      .when('/about', {
          templateUrl: 'views/about.html',
          controller: 'aboutController'
      })
      .otherwise({
          redirectTo: '/'
      });
}])
.controller('mainController', function ($scope) {
    $scope.message = "Main Content";
});;

Here in the “app.js”, there are some couple of key components. Since our application is Single Page Application, we don’t want any page refreshes. Here we are using AngularJS routing capabilities by injecting $routeProvider in AngularJS. There I am saying when the Url is “/” load the “views/home.html” which is bound to “homeController”. When the Url is “/about”, same way load the “views/about.html” which is bound to “aboutController”. There is also a controller defined “mainController”.

Now let’s go ahead with creating "home" and "about" views and controllers. I am adding two JavaScript files named “homeController” and “aboutController” inside “App/controllers” folder.
image
controllers folder
homeController.js
'use strict';

app.controller('homeController', function ($scope) {
    $scope.message = "Now viewing home!";
});
aboutController.js
'use strict';

app.controller('aboutController', function ($scope) {
    $scope.message = "Now viewing about!";
});
Now let’s create the views.
image
views folder
home.html
<div ng-controller="homeController">
    <h2>{{message}}</h2>
</div>
about.html
<div ng-controller="aboutController">
    <h2>{{message}}</h2>
</div>

Now let’s modify the “Index.html” integrating all together and defining which displays where.

Index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" ng-app="myApp">
<head>
    <title>Sample AngularJS project using Visual Studio</title>
    <script src="../Scripts/angular.js"></script>
    <script src="../Scripts/angular-route.js"></script>
    <script src="app.js"></script>
    <script src="controllers/homeController.js"></script>
    <script src="controllers/aboutController.js"></script>
</head>
<body>
    <div>
        <a href="#/">Home</a>
        <a href="#/about">About</a>
    </div>

    <div ng-controller="mainController">
        <h1>{{message}}</h1>
        <div ng-view>
        </div>
    </div>
</body>
</html>

Here first in <html>, I have mentioned ng-app directive, which powers up the AngularJS. Then in the <head></head> section, I have included all the necessary scripts. Then in <body></body> section, first I have added a <div> which will contain links for navigation. For linking to pages, # (hash tag) is used. We don’t want the browser to think we are actually travelling to “home.html” or “about.html”.

Then defined a <div> which is bound to “mainController”. There first I am displaying the value in $scope.message in “mainController”. Then I have a ng-view which defines a angular template and the templates will be injected inside ng-view.

So that’s it. When we run the project I am getting the following output.

Here note the Url is “/”
image
Home
Here note the Url is “/about”.
image
About
And when we are navigating between “Home” and “About”, there is no page refreshing.

So hope you found this interesting. I am uploading the full sample to OneDrive. Enjoy!.


Happy Coding.

Regards,
Jaliya

27 comments:

  1. Brilliant .. this is exactly what I have been looking for a clean setup for AngularJS in an ASP.NET Web Application. I too have separately developed Wep API.

    Question .. if running this under IIS Express (Default VS IIS) ... how did you get it to run without specifying the index.html in url ... I have set startup page to index.html but I just want to start with http://localhost:52108 ... or is this something I can only do with Local IIS ?

    ReplyDelete
    Replies
    1. Hi,

      Right click on the project, under Web tab, set the project Url.

      Delete
  2. Thanks for this very simple to follow and great AngularJS sample project!

    ReplyDelete
  3. Thank You Very Much!!! I've been looking for something like this for days!!!

    ReplyDelete
  4. This is exactly what I needed! Thank you very much!

    ReplyDelete
  5. Excellent. Very nice job. Thanks much for putting this out.

    ReplyDelete
  6. You have no idea how thankful I am for finding this quick tutorial. I've been wanting to start dabbling in web development and the default tutorials just throw everything in the bucket and seem to expect folks to read through all of the included files in the 'basic' setup to know what is going on. I don't learn that way. Your tutorial, starting with a blank project and building up, is exactly what I need to learn things.

    ReplyDelete
  7. onk valo jinis.. dhonnobad :)

    ReplyDelete
  8. Not sure if my last comment made it, but just wanted to say awesome effort! Thanks again.

    ReplyDelete
  9. Not sure if my last comment made it but just wanted to say thank you! Many other tutorials cover more than the basics for the beginner (e.g. node.js, etc). AWESOME EFFORT! Thank you again, you're a legend.

    ReplyDelete
  10. Thanks for sharing the tutorial.
    I am still unable to run the application through http://localhost:port_no.
    Can you help me with that?

    ReplyDelete
  11. Thanks. It's an excellent article. Do you have any sample(s) on developing/designing website with angularjs and bootstrap?

    ReplyDelete
  12. your article helped me a lot to sharpen my skills and do well in my interview. One of trainer from leading dot net training institutes in Chennai suggests me about your site.

    ReplyDelete
  13. Hello Jaliya, I have been training students on AngularJS for past 6 months, and at times, I have used your blog as reference for the class training and also for my personal project development. It has been so much useful. Thank you, keep writing more:)
    Shashaa
    AngularJS course in Chennai

    ReplyDelete
  14. Awesome post for beginners. Thank you!!

    ReplyDelete
  15. This is an Excellent way of understanding and for organizing the folder structures in AngularJS.

    ReplyDelete
  16. Great Work. very good step by step explanation.

    AngularJs Training

    ReplyDelete
  17. Its really very nice and informative post. thanks for shearing the great ideas.
    Web Development

    ReplyDelete
  18. nice post for sharing angularjs article. its really helpful for me.keep shring on updated angularjs tutorials????????????????

    ReplyDelete