Wednesday 8 February 2017

ASP.Net MVC + AngularJS for Application Development

Hello Friends,

Today,  we are going to discuss about MVC architecture and AngularJS for Application development.

I didn’t get a chance to work on MVC based applications earlier and used AngularJS slightly while many of my team member was working on MVC. 

So, finally I also decided to explore about MVC but when I started I came to know that MVC alone is not being used in most cases now but popular in application development along with AngularJS. But, when I started looking into it without prior much knowledge in MVC, I started with struggle in MVC + AngularJS parts being handled and understanding of related application development. 

So, we will discuss mainly about very basic problem I faced during my initial exploring and small introduction of other facts.

So, lets’s quickly discuss basic stuffs related to this topic.

1. MVC
2. AngularJs

MVC:- As we all knows that MVC stands for Model-View-Controller architecture of development which separates an application into three logical components. Where.

Model - Is associated and responsible for database related logic and operations.

View - Represents UI to display data/information to users and to allows user to perform operations.

Controller - It works as interface between View and Model and actually responsible to process requests and operation from view and processing data using model.

The ASP.NET MVC framework is a lightweight, highly testable presentation framework that is integrated with existing ASP.NET features, such as master pages, authentication, etc. Within .NET, this framework is defined in the System.Web.Mvc assembly. The latest version of the MVC Framework is 5.0. We use Visual Studio to create ASP.NET MVC applications which can be added as template in Visual Studio.

For more details and quick learning, refer below URLs

https://www.asp.net/mvc/overview/getting-started/introduction/getting-started
https://www.tutorialspoint.com/mvc_framework/mvc_framework_introduction.htm

2. AngularJs :- AngularJS (commonly referred to as "Angular" or "Angular.js") is a completely JavaScript-based open-source front-end web application framework mainly maintained by Google and by a community of individuals and corporations to address many of the challenges encountered in developing single-page applications.

AngularJS is a JavaScript framework. It is a library written in JavaScript. AngularJS is distributed as a JavaScript file, and can be added to a web page with a script tag:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

AngularJS extends HTML attributes with Directives, and binds data to HTML with Expressions.

For more details and quick learning, refer below URLs

https://docs.angularjs.org/guide/introduction
http://www.w3schools.com/angular/angular_intro.asp

Now, let’s come to the problem that I faced initially when tried to merge MVC and AngularJS for web application development.

Basically, MVC is itself has MVC architecture but AngularJS is also used with MVC architecture. So there was the problem arises when started to explore that what is the scope of MVC of Angular and Asp.Net MVC. It was bit confusing to me that why we need ASP.Net MVC while using AngularJS MVC. Because AngularJS MVC is dealing most of the part of application flow from front end and I concluded that this is true that Asp.Net MVC can be skipped and MVC Web API could be used to get any data from server side but then realize that this is OK but for authentication and basic stuff it will become a pain to handle authentication using API within same application while considering security concerns.

Then I rethink and found that in MVC + Angular, actually basic stuffs like authentication etc are being handled through Asp.Net MVC while all other front end level operation being handled by Angular MVC.

But to configure and setup application using MVC and angular was bit tricky according to me. So I am trying to specify exact steps to make it bit easier for new learners like me.

Below are the steps that can be followed to make it working while using MVC and AngularJS.
1. Open Visual Studio 12 or above and open New Project
2. Create ASP.Net Web Application
3. Select MVC as template to be used
4. Uninstall default added packages through package manager console. Use below commands to uninstall.
Uninstall-Package Microsoft.jQuery.Unobtrusive.Validation
Uninstall-Package jQuery.Validation
Uninstall-Package jQuery
Uninstall-Package Modernizr
Uninstall-Package Respond
Uninstall-Package bootstrap

5. Remove reference of above from BundleConfig.cs as well (Optional)
6. Remove Default controllers and views added (optional)
7. Open Index.html in Views -> Home and delete contents.
8. Download AngularJS library and add in your project structure (in Scripts folder - recommendation but not necessary)
9. Add blank page with reference to your angular.js library file in your folder structure like below

<!DOCTYPE html>
<html ng-app>
<head>
    <title></title>
</head>
<body>
    <script src="~/Scripts/libs/angular.js/1.2.20/angular.min.js"></script>
</body>
</html>

10. Now if all is well then your application is ready to use angular js. So add some Angular JS code on your index.html in body tag. For Ex. as below
    
    <input type="text" ng-model="helloAngular" />
    <h1>{{helloAngular}}</h1>

11. This looks okay but still angular not using MVC here. So, we need to update our folder structure a little bit with following.
      a)Add a folder in Scripts for your App's Angular MVC “/Scripts/AngularMVC/”
      b)Add a js file with your application name (i.e. "MVCWebAppDemo") in "/Scripts/AngularMVC/"
      c)Add folder “Controllers” in “AngularMVC” and add a js file named as "HomePageController" in controllers folder.


12. Now add your application AngularMVC script files in bundle in "App_Start/BundleConfig.cs"

bundles.Add(new ScriptBundle("~/bundles/MVCWebAppDemo").IncludeDirectory("~/Scripts/AngularMVC/Controllers", "*.js").Include("~/Scripts/AngularMVC/MVCWebAppDemo.js"));

13. Now add this bundle to the homepage (index), after the angular.min script tag itself:

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

14. Add code in AngularJS MVC controllers (i.e."HomePageController.js" ) (to control and process requests) as below.

var HomePageController = function($scope) {    $scope.models = {
helloAngular: 'I am home page!'    }; }
// The $inject property of every controller (and pretty much every other type of object in 
//Angular) needs to be a string array equal to the controllers arguments, only as strings

HomePageController.$inject = ['$scope'];

15. Now setup our application object (i.e. ApplicationName.js as added in angularMVC folder) to indicate controller to be used.

//This creates an app module object for angular app.
var MVCWebAppDemo = angular.module('MVCWebAppDemo',[]); 

//Add controller information in this app/module now. //Here we registered HomePageController as created in "/Scripts/AngularMVC/Controllers/HomePageController.js"

MVCWebAppDemo.controller('HomePageController', HomePageController) 

16. Now configure homepage to know about configured Angular App/module and associated controller.
      a) add "ng-app" directive in <html> tag to specify angular app/module name 
      
      b) add "ng-controller" directive in <html> tag to specify controller name to be used from added angular app/module

For Ex. - 
<html ng-app="MVCWebAppDemo" ng-controller="HomePageController">

17. Now run the application. If all done well you should see home page with message as "I am home page!"

So far we are good to configure ASP.net MVC Application which is using AngularJS in MVC structure but we have not yet used anything from ASP.Net MVC explicitly. Internally it is already working.

Now consider a situation where we need some data processed through ASP.Net server side and MVC is responsible for that. So, to understand that how server side controllers are being triggered and refer for request processing, we are going to use simple routing and will pass some data from ASP.Net MVC controller which will appear at front end.  

18. Create a new link on home page (index.html) to navigate to products as below

<ul>
        <li><a href="/#/products">Show Product</a></li>
</ul>

19. Add a div to render partial views. Create a view and add ng-view directive in this.

<div ng-view></div>

20. Add ngRoute module of Angular JS and load in your application by adding it as dependent module.
      a)Download/refer angular-route.js and add on home page below angularJS.

      <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular-route.min.js"></script>

      b) Add ngRoute in application module as dependent

       var MVCWebAppDemo = angular.module("MVCWebAppDemo", ['ngRoute']);

21. Now map routes being used in application. In our example "/products". So add below code in application module (i.e. MVCWebAppDemo.js)

var configFunction = function ($routeProvider) {
    $routeProvider.
        when('/products', {
            templateUrl: 'product/get'
        });
}
configFunction.$inject = ['$routeProvider'];
MVCWebAppDemo.config(configFunction);

22. Now observe above specified ConfigFunction for below code

$routeProvider.when('/products', { templateUrl: 'product/get' });

23. In above code 
      a) '/products' is client side URL called in browser
      b) templateURL is used to specify internal URL/MVC URL (i.e. "product/get")           that need to be processed and according to this internal URL respective             controller with specific action (i.e. "get" action of "ProductController" in             our example above) will be triggered.

          Note:- Please refer that default configuration for MVC URL is 
          "/Controller/Action/Id". 

So if we refer specified templateURL (I.e. “product/get”) that means it will trigger “get” function of “Product” controller. But product controller is not yet added so lets add “ProductController”

24. Now add an empty MVC controller in "/Controllers" folder and  name it as ProductController and add below code in it.
      
  public ActionResult get()
        {
         List<string> productList = new List<string>();
            productList.Add("Product 1");
            productList.Add("Product 2");
            productList.Add("Product 3");
            ViewBag.products = productList; 
return View("_products");
        }

Please not that in above code we are returning "_products" view from get action. But this is not yet created. So follow next step to add a new view.

25. Go to "/Views/Product/" folder in solution explorer and add a partial view and name it as "_products" with below code in it to render results.

Product List
<ul>
    @for (int i = 0; i < ViewBag.products.Count; i++)
    {
        <li>@ViewBag.products[i]</li>
    }
</ul>

26. Now run application and if all configured correctly then you should see same home page with “Products” link on it and when click on “Products” link then it should display “Product 1”, “Product 2”, “Product 3” below the link.

So, as we seen that how we used ASP.Net MVC and AngularJS together. Now you are free to explore more as per your requirement and can manage most of front end business logics through AngularJS MVC also powered with ASP.Net MVC server side processing.

I hope this may help some newbies who is struggling with setup/configuration of ASP.Net MVC along with AngularJS. So keep sharing feedback if this help anyone or let me know feedback to improve it. 

Alright, so, see you soon, till then keep exploring and sharing.

References