ASP.NET MVC 5 With AngularJS - Part One

Introduction


AngularJS the way I learned, I thought to share with the audience who are searching for learning AngularJS in a simplified way. This article is for them.

Here's the flow of this article which we will get into step by step. Firstly, we will pick with what & why.
  • What is AngularJS?
  • Why named AngularJS?
  • Why another JavaScript framework? JQuery VS Angular.
  • We will differentiate them with an example.
  • Download & Install AngularJS Library in Visual Studio 2015.
  • Start AngularJS with Visual Studio.
  • We will submit a form with AngularJS.
  • About Form State
  • Send form data to MVC Controller.
  • Make URL (# free) in AngularJS.

Ok, let's get started. Before we focus on any topic let's know what is AngularJS.

what is AngularJS

What is AngularJS


AngularJS is a client-side JavaScript MVC-Based framework. It is Open source, supported & maintained by Google. AngularJS as “Angular” or “Angular.js” was initially released in 2009, which goal to enhanced the development process and testing.

Why named AngularJS

We know HTML that is contained (eg: <html>) with angle brackets(<>) thus the name[according to FAQ] came "Angular". AngularJS uses directives like ng-app, ng-model that prefixed with "ng"(base directive) which bring to mind "Angular".

Why another JavaScript framework

Why another JavaScript framework

Both are purposed to client-side scripting, but AngularJS simply offers more features and advantages. As we know that AngularJS is MVC-Based framework which is modular and reusable.

 

Here's an overview of both:

AngularJS
  • Google supported & maintained open source JavaScript MVC framework.
  • Smart Data-binding
  • Use MVC design pattern.
  • Form Validations
  • Supports routing (Single Page Application).
  • Uses Dependency Injection(DI).
  • Easy to Unit test
  • Modular & reusable architecture
  • REST-friendly

JQuery

  • Lightweight open source JavaScript framework
  • Great tool for manipulating and controlling DOM elements

Example:

AngularJS

  1. <body ng-app>  
  2.     First Name: <input type="text"ng-model="fname"/><br/>  
  3.     Last Name: <input type="text"ng-model="lname"/><br/>  
  4.     Result: {{fname+''+lname}}  
  5. </body>  
  6. </html>  
  7. <script src="Scripts/angular.min.js"></script>  
JQuery
  1. <body>  
  2.     First Name: <inputtype="text"id="txtfName"/><br/>  
  3.     Last Name: <inputtype="text"id="txtlName"/><br/>  
  4.     Result: <labelid="lblName"></label>  
  5. </body>  
  6. </html>  
  7. <script src="Scripts/jquery-2.2.0.min.js"></script>  
  8. <script type="text/javascript">  
  9.     $(document).ready(function () {  
  10.         $(function () {  
  11.             $('#txtfName').keyup(function () {  
  12.                 $('#lblName').text($('#txtfName').val() + ' ' + $('#txtlName').val());  
  13.             });  
  14.   
  15.             $('#txtlName').keyup(function () {  
  16.                 $('#lblName').text($('#txtfName').val() + ' ' + $('#txtlName').val());  
  17.             });  
  18.         });  
  19.     });  
  20. </script>  
Isn’t it cool? The main thing is both the results are same.

Ok, let’s get started with AngularJS: First test with a simple website in Visual Studio 2015.

Download & Install AngularJS Library in Visual Studio 2015


Go to AngularJS website and download.

Download AngularJS

Click on the Download link to download the latest version of AngularJS library.

AngularJS with Visual Studio

Let’s open Visual Studio 2015(IDE) click: File, New, Project and then the new window will appear like the following image:

ASP.Net Web Application
Figure 1.0

Click on ASP.NET Web Application, rename the application and hit “ok” button at bottom right. Choose empty template in next window and click on “ok” button. It will take a while to load a sample empty project.

Now the first thing we need to do is register AngularJS.Core in this application. We need to get reference from NuGet.

To do that right click on project name and click on “Manage NuGet Packages” like the following image.

Manage newget package
Figure 1.1

And in next window browse searching “Angular” and install the updated version of AngularJS.Core like the following image:

AngularJS
Figure 1.2

Or click on Tools, NuGet Package Manager, then Package Manager Console and write Install-Package AngularJS.Core, also we need to add jQuery library in our project like below:

JQuery
Figure 1.3

Our Installation process is done. Now test it with our previous AngularJS code in comparison with jQuery section.

Let’s add a new HTML page and name it “Index”.

add html page
Figure 1.4

Code in Index.html
  1. <body ng-app> First Name:  
  2.     <input type="text" ng-model="fname" />  
  3.     <br/> Last Name:  
  4.     <input type="text" ng-model="lname" />  
  5.     <br/> Result: {{fname+''+lname}} </body>  
  6.   
  7.     </html>  
  8.     <script src="Scripts/angular.min.js">  
  9. </script>  
Notice that the above example is a simple HTML code, but there are some new unknown attributes and braces.

The new attributes "ng-app", "ng-model" are AngularJS directives, and the "{{}}" is expression. Later we will discuss about those.

Well, what is AngularJS directives? AngularJS directives extends the HTML attributes with the prefix "ng".

Know more about AngularJS directives here.

Output

see output

Form with AngularJS

Let’s add a new MVC empty project to work with form and later we will send the data to Controller. To do that right click on the existing solution, click: File, New, then Project and name it “AngularJSForm“.

Add new project
Figure 1.5

Now register AngularJS library and others repeating Fig:1.1 – 1.3.

In the controller folder let’s create HomeController class and generate View.

Add view
Figure 1.6

Let’s goto Views, Shared, then _layout.cshtml and add Module, this is the start point where application should be bootstrapped.
  1. <bodyng-app="myFormApp">  
Form:
  1. <div id="content" ng-controller="CustomerController">  
  2.     <span ng-show="isViewLoading" class="viewLoading">  
  3.         <img src="~/Content/images/ng-loader.gif" /> loading... </span>  
  4.         <div ng-class="result">{{message}}</div>  
  5.             <hr/>  
  6.             <form ng-submit="submitForm()" name="frmCustomer">  
  7.                 <div>  
  8.                     <label for="email">Customer Name</label>  
  9.                         <input type="text" ng-model="cust.CustName" name="cname" placeholder="Enter your name" requiredng-minlength="4" ng-maxlength="14" />  
  10.                         <span class="error" ng-show="(frmCustomer.$dirty||submitted)&&frmCustomer.cname.$error.required">Customer name is Required</span>  
  11.                             <span class="error" ng-show="frmCustomer.$dirty&&frmCustomer.cname.$error.minlength">Minimum length required is 5</span>  
  12.                                 <span class="error" ng-show="frmCustomer.$dirty&&frmCustomer.cname.$error.maxlength">Minimum length required is 15</span>  
  13.                 </div>  
  14.                 <div>  
  15.                     <label for="email">E-mail address</label>  
  16.                         <input type="email" ng-model="cust.CustEmail" name="email" placeholder="Enter your Email" required/>  
  17.                         <span class="error" ng-show="(frmCustomer.$dirty||submitted)&&frmCustomer.email.$error.required">EmailId is Required!</span>  
  18.                             <span class="error" ng-show="(frmCustomer.$dirty||submitted)&&frmCustomer.$error.email">Invalid EmailId!</span>  
  19.                 </div>  
  20.                 <div>  
  21.                     <input type="submit" value="Submit" ng-disabled="myForm.$invalid">  
  22.                 </div>  
  23.             </form>  
  24.         </div>  
Script:
  1. @section JavaScript  
  2. { < script src = "~/Scripts/jquery-1.10.2.min.js" > < /script> < script src = "~/Scripts/angular.min.js" > < /script> < scriptsrc = "~/Scripts/angular-route.min.js" > < /script> < script > angular.module('myFormApp', []).  
  3.     controller('CustomerController', function ($scope, $http, $location, $window)  
  4.     {  
  5.         $scope.cust = {};  
  6.         $scope.message = '';  
  7.         $scope.result = "color-default";  
  8.         $scope.isViewLoading = false;  
  9.         //get called when user submits the form  
  10.         $scope.submitForm = function ()  
  11.         {  
  12.             $scope.isViewLoading = true;  
  13.             console.log('Form is submitted with:', $scope.cust);  
  14.             //$http service that send or receive data from the remote server  
  15.             $http(  
  16.             {  
  17.                 method: 'POST',  
  18.                 url: '/Home/CreateCustomer',  
  19.                 data: $scope.cust  
  20.             }).success(function (data, status, headers, config)  
  21.             {  
  22.                 $scope.errors = [];  
  23.                 if (data.success === true)  
  24.                 {  
  25.                     $scope.cust = {};  
  26.                     $scope.message = 'Form data Submitted!';  
  27.                     $scope.result = "color-green";  
  28.                     $location.path(data.redirectUrl);  
  29.                     $window.location.reload();  
  30.                 }  
  31.                 else  
  32.                 {  
  33.                     $scope.errors = data.errors;  
  34.                 }  
  35.             }).error(function (data, status, headers, config)  
  36.             {  
  37.                 $scope.errors = [];  
  38.                 $scope.message = 'Unexpected Error while saving data!!';  
  39.             });  
  40.             $scope.isViewLoading = false;  
  41.         }  
  42.     }).config(function ($locationProvider)  
  43.     {  
  44.         //default = 'false'  
  45.         $locationProvider.html5Mode(true);  
  46.     }); < /script>  
  47. }  
Form Style
  1. <style>  
  2. #content label {  
  3.     width150px;  
  4. }  
  5.   
  6. #content input[type=submit] {  
  7.     margin-left154px;  
  8.     width120px;  
  9.     padding5px15px;  
  10.     background#ff6a00;  
  11.     border0none;  
  12.     cursorpointer;  
  13.     color#fff;  
  14. }  
  15.   
  16. .error {  
  17.     colorred;  
  18. }  
  19.   
  20. .color-default {  
  21.     color#000;  
  22. }  
  23.   
  24. .color-red {  
  25.     colorred;  
  26. }  
  27.   
  28. .color-green {  
  29.     colorgreen;  
  30. }  
  31.   
  32. #content input.ng-dirty.ng-invalid {  
  33.     border1pxsolidred;  
  34.     background-color#fff4f4;  
  35. }  
  36. </style>  
Output

Result
Code Explanation

In our form example we have some new attributes "ng-app, ng-controller, ng-show, ng-class, ng-submit, ng-model, ng-disabled". we have seen “ng-model ” use in our first example.

Those all are AngularJS directives.

Let's discuss with the AngularJS application start point, the Module. What is module in AngularJS?

Module: Module is nothing but a container of the different parts of an application such as controller, service, filters, directives, factories, etc.

Module defines where the application should be bootstrapped.

angular.module('myFormApp', [])


This is a module method which has two parameters. 
  1. The first parameter is module name, that reference to "myFormApp" module in <body ng-app="myFormApp"> which is same as specified by ng-app directive. This is what bootstraps the app using our module.

  2. The second parameter is an empty[] array in "angular.module(‘myFormApp’, [])" method. This array is the list of other dependent modules.

Next focus to JavascriptController(CustomerController)

JavaScript Controller

  1. .controller('CustomerController', function ($scope) {  
  2.    //inner code  
  3. });  
Controller is a JavaScript function in AngularJS. The ng-controller directive in <div id=”content” ng-controller=”CustomerController”> defines the application controller.

Using $scope object the controller control the application behavior. Well then, what is $scope?

$scope: Scope is an "object" that "binds together" to DOM element where controller relay. Simply, scope connect between the HTML View & the JavaScript Controller.
 
Know more about $scope here 

HTML View:
  1. <div ng-class="result">{{message}}</div>  
JavaScript Controller:
  1. .controller('CustomerController', function ($scope) {  
  2.    $scope.message = 'Show in view';  
  3. })  
Let's discuss about the validations of the form.

Validations

Validations check that the information that users enter is valid or not. AngularJS also have form validation features like JQuery/JQueryUnobtrusive Validation. Here we will overview some of them.

Know more about Custom Validation here.

Required Field Validator: To validate users empty input with AngularJS we used HTML5 attribute "required" or we can use ng-required="true" .
  1. <inputtype="email"ng-model="cust.CustEmail"name="email"required/>  
Validation Message:
  1. <spanclass="error"ng-show="(frmCustomer.$dirty||submitted)&&frmCustomer.email.$error.required">EmailId is Required!</span>  
Range Validator: To validate user input by range with AngularJS we used HTML5 attribute "ng-minlength, ng-maxlength".
  1. <inputtype="text"ng-model="cust.CustName"name="cname"requiredng-minlength="4"ng-maxlength="14"/>  
Validation Message:
  1. <spanclass="error"ng-show="frmCustomer.$dirty&&frmCustomer.cname.$error.minlength">Minimum length required is 5</span>  
  2.   
  3. <spanclass="error"ng-show="frmCustomer.$dirty&&frmCustomer.cname.$error.maxlength">Minimum length required is 15</span>  
Type Validation: To validate the email type we can use this in AngularJS.
  1. <spanclass="error"ng-show="(frmCustomer.$dirty||submitted)&&frmCustomer.$error.email">Invalid EmailId!</span>  
Updating the Form State

AngularJS itself has some properties to updating the state of the form. They are true or false.
  • $ error: Object contains all the validation attributes applied to the specified element.
  • $ pristine: True if the user has not interacted with control yet else returns false.
  • $ valid: True if the model is valid
  • $ invalid: True if the model is invalid
  • $ dirty: True if user changed the value of model at least once
  • $ touched: True if the user has tabbed out from the control.
  • $ untouched: True if the user has not tabbed out from the control.

Send Form data to MVC Controller

To submit the form to MVC Controller we need to add a new method in our HomeController and we need to modify our CustomerController in script section.

In HomeController we need to add the following method.

  1. [HttpPost]  
  2. public JsonResultCreateCustomer(Customer model)  
  3. {  
  4.     if (ModelState.IsValid)  
  5.     {  
  6.         //Data save to database  
  7.         returnJson(new  
  8.         {  
  9.             success = true  
  10.         });  
  11.     }  
  12.     return Json(new  
  13.     {  
  14.         success = false,  
  15.             errors = ModelState.Keys.SelectMany(i => ModelState[i].Errors).Select(m => m.ErrorMessage).ToArray()  
  16.     });  
  17. }  
Let's modify our JavascriptCustomerController.
  1. angular.module('myFormApp', []).  
  2. controller('CustomerController', function ($scope, $http)  
  3. {  
  4.     $scope.cust = {};  
  5.     $scope.message = '';  
  6.     $scope.result = "color-default";  
  7.     $scope.isViewLoading = false;  
  8.     //get called when user submits the form  
  9.     $scope.submitForm = function ()  
  10.     {  
  11.         $scope.isViewLoading = true;  
  12.         console.log('Form is submitted with:', $scope.cust);  
  13.         //$http service that send or receive data from the remote server  
  14.         $http(  
  15.         {  
  16.             method: 'POST',  
  17.             url: '/Home/CreateCustomer',  
  18.             data: $scope.cust  
  19.         }).success(function (data, status, headers, config)  
  20.         {  
  21.             $scope.errors = [];  
  22.             if (data.success === true)  
  23.             {  
  24.                 $scope.cust = {};  
  25.                 $scope.message = 'Form data Submitted!';  
  26.                 $scope.result = "color-green";  
  27.             }  
  28.             else  
  29.             {  
  30.                 $scope.errors = data.errors;  
  31.             }  
  32.         }).error(function (data, status, headers, config)  
  33.         {  
  34.             $scope.errors = [];  
  35.             $scope.message = 'Unexpected Error while saving data!!';  
  36.         });  
  37.         $scope.isViewLoading = false;  
  38.     }  
  39. });  
Let’s put a breakpoint on CreateCustomer() method in HomeController and run it, after submitting the form it’ll hit the breakpoint.

Home controller
Figure 1.7

In debug mode we can see the model is populated with form data, which we can send it to database & save the data.

Output:

Output
Output is same as before.

Code Explanation

In the above example of sending form data to Controller we have used $http service. Well then what are those? 
  • Service: AngularJS services are JavaScript functions to relate with the controller, model or custom directives. AngularJS also have other useful services like $interval, $window, $log. To know more about services click here.

  • $http service: We can use $http service to send an AJAX request. In this example we have sent Http POST request to the remote server to submit the data.

Make URL HashTag(#) free in AngularJS

Next we will redirect to new URL after form submission using $location service. Using $location service AngularJS add ‘#’ to the url which prevent to redirect to a desired url.

Know more about $locationProvider here.

To solve this by removing ‘#’ from URL we need to Inject $locationProvider in config() function of angular root module then set html5Mode() to true. 
  1. .config(function ($locationProvider) {  
  2.    $locationProvider.html5Mode(true);  
  3. });  
In the script section we need to modify our CustomerController and add two new line of code which will indicate the path and redirect with full page reload.
  1. $location.path(data.redirectUrl);  
  2. $window.location.reload();  
Add base tag in head section(_Layout.cshtml) of master page/layout of application.
  1. <basehref="/">  
Finally CustomerController(Javascript):
  1. angular.module('myFormApp', []).  
  2. controller('CustomerController', function ($scope, $http, $location, $window)  
  3. {  
  4.     $scope.cust = {};  
  5.     $scope.message = '';  
  6.     $scope.result = "color-default";  
  7.     $scope.isViewLoading = false;  
  8.     //get called when user submits the form  
  9.     $scope.submitForm = function ()  
  10.     {  
  11.         $scope.isViewLoading = true;  
  12.         console.log('Form is submitted with:', $scope.cust);  
  13.         //$http service that send or receive data from the remote server  
  14.         $http(  
  15.         {  
  16.             method: 'POST',  
  17.             url: '/Home/CreateCustomer',  
  18.             data: $scope.cust  
  19.         }).success(function (data, status, headers, config)  
  20.         {  
  21.             $scope.errors = [];  
  22.             if (data.success === true)  
  23.             {  
  24.                 $scope.cust = {};  
  25.                 $scope.message = 'Form data Submitted!';  
  26.                 $scope.result = "color-green";  
  27.                 $location.path(data.redirectUrl);  
  28.                 $window.location.reload();  
  29.             }  
  30.             else  
  31.             {  
  32.                 $scope.errors = data.errors;  
  33.             }  
  34.         }).error(function (data, status, headers, config)  
  35.         {  
  36.             $scope.errors = [];  
  37.             $scope.message = 'Unexpected Error while saving data!!';  
  38.         });  
  39.         $scope.isViewLoading = false;  
  40.     }  
  41. }).config(function ($locationProvider)  
  42. {  
  43.     //default = 'false'  
  44.     $locationProvider.html5Mode(true);  
  45. });  
Finally HomeController(MVC):
  1. public class HomeController: Controller  
  2. {  
  3.     // GET: Home  
  4.     publicActionResult Index()  
  5.     {  
  6.         return View();  
  7.     }  
  8.     [HttpPost]  
  9.     public JsonResultCreateCustomer(Customer model)  
  10.     {  
  11.         if (ModelState.IsValid)  
  12.         {  
  13.             //Data save to database  
  14.             varRedirectUrl = Url.Action("About""Home"new  
  15.             {  
  16.                 area = ""  
  17.             });  
  18.             returnJson(new  
  19.             {  
  20.                 success = true, redirectUrl = RedirectUrl  
  21.             });  
  22.         }  
  23.         returnJson(new  
  24.         {  
  25.             success = false,  
  26.                 errors = ModelState.Keys.SelectMany(i => ModelState[i].Errors).Select(m => m.ErrorMessage).ToArray()  
  27.         });  
  28.     }  
  29.     // GET: Home/About  
  30.     public ActionResult About()  
  31.     {  
  32.         return View();  
  33.     }  
  34. }  
Output

Run
About
Points of Interest

Next part we will create a sample application with AngularJS to perform CRUD operations with ASP.NET MVC. 
 
Next part of this series:  


Similar Articles