In this topic we will overview on AngularJS, after getting an overview we will create a ASP.Net MVC application with implementing AngularJS(v1.4.8).
Introduction
I have prepared this article to share/clear concept about AngularJS the way i learnt. I thought to share with audience who are searching for learning to AngularJS in simplyfied way. This article is for them.
Here’s the flow of this article which we will get into step by step. First 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 any topic let’s know 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 enhance the development process and testing.
Know more about Client side here.
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?
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 manipulate and control DOM elements
Example:
AngularJS-
<body ng-app> First Name: <input type="text" ng-model="fname" /> <br /> Last Name: <input type="text" ng-model="lname" /> <br /> Result: {{fname +' '+ lname}} </body> </html> <script src="Scripts/angular.min.js"></script>
JQuery-
<body> First Name: <input type="text" id="txtfName" /> <br /> Last Name: <input type="text" id="txtlName" /> <br /> Result: <label id="lblName"></label> </body> </html> <script src="Scripts/jquery-2.2.0.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $(function () { $('#txtfName').keyup(function () { $('#lblName').text($('#txtfName').val() + ' ' + $('#txtlName').val()); }); $('#txtlName').keyup(function () { $('#lblName').text($('#txtfName').val() + ' ' + $('#txtlName').val()); }); }); }); </script>
isn’t it cool? The main thing is both are results 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 – https://angularjs.org
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] the new window will appear like below image
Fig: 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 getting reference from NuGet.
To do that right click on project name and click on “Manage NuGet Packages” like below image
Fig: 1.1
and in next window browse searching “Angular” and install the updated version of AngularJS.Core like below image
Fig: 1.2
Or click on [ Tools > NuGet Package Manager > Package Manager Console ] and write
Install-Package AngularJS.Core
also we need to add jQuery library in our project like below.
Fig: 1.3
Our Installation process is done. Now test it with our previous AngularJS code in comparing with jQuery section.
Let’s add a new HTML page and name it “Index”.
Fig: 1.4
Code in Index.html
<body ng-app> First Name: <input type="text" ng-model="fname" /> <br /> Last Name: <input type="text" ng-model="lname" /> <br /> Result: {{fname +' '+ lname}} </body> </html> <script src="Scripts/angular.min.js"></script>
Notice that the above example is a simple HTML code, but there are some new unknown attributes and braces are consist.
The new attributes “ng-app”, “ng-model” are AngularJS directives, and the “{{}}” is expression. Later we will discus about those.
Well what is AngularJS directives? AngularJS directives extends the HTML attributes with the prefix “ng”.
Know more about AngularJS directives here.
Output:
Form with AngularJS:
Let’s add a new MVC empty project to work with form later we will send the data to Controller. To do that right click on the existing solution click : [File > New > Project] name it “AngularJSForm“.
Fig: 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.
Fig: 1.6
Let’s goto [Views > Shared > _layout.cshtml] and add Module, this is the start point where application should be bootstrapped.
<body ng-app="myFormApp">
Form:
<div id="content" ng-controller="CustomerController"> <span ng-show="isViewLoading" class="viewLoading"> <img src="~/Content/images/ng-loader.gif" /> loading... </span> <div ng-class="result">{{message}}</div> <hr /> <form ng-submit="submitForm()" name="frmCustomer"> <div> <label for="email">Customer Name</label> <input type="text" ng-model="cust.CustName" name="cname" placeholder="Enter your name" required ng-minlength="4" ng-maxlength="14" /> <span class="error" ng-show="(frmCustomer.$dirty||submitted) && frmCustomer.cname.$error.required">Customer name is Required</span> <span class="error" ng-show="frmCustomer.$dirty && frmCustomer.cname.$error.minlength">Minimum length required is 5</span> <span class="error" ng-show="frmCustomer.$dirty && frmCustomer.cname.$error.maxlength">Minimum length required is 15</span> </div> <div> <label for="email">E-mail address</label> <input type="email" ng-model="cust.CustEmail" name="email" placeholder="Enter your Email" required /> <span class="error" ng-show="(frmCustomer.$dirty ||submitted) && frmCustomer.email.$error.required">EmailId is Required!</span> <span class="error" ng-show="(frmCustomer.$dirty ||submitted) && frmCustomer.$error.email">Invalid EmailId!</span> </div> <div> <input type="submit" value="Submit" ng-disabled="myForm.$invalid"> </div> </form> </div>
Script:
@section JavaScript{ <script src="~/Scripts/jquery-1.10.2.min.js"></script> <script src="~/Scripts/angular.min.js"></script> <script src="~/Scripts/angular-route.min.js"></script> <script> angular.module('myFormApp', []). controller('CustomerController', function ($scope, $http, $location, $window) { $scope.cust = {}; $scope.message = ''; $scope.result = "color-default"; $scope.isViewLoading = false; //get called when user submits the form $scope.submitForm = function () { $scope.isViewLoading = true; console.log('Form is submitted with:', $scope.cust); //$http service that send or receive data from the remote server $http({ method: 'POST', url: '/Home/CreateCustomer', data: $scope.cust }).success(function (data, status, headers, config) { $scope.errors = []; if (data.success === true) { $scope.cust = {}; $scope.message = 'Form data Submitted!'; $scope.result = "color-green"; $location.path(data.redirectUrl); $window.location.reload(); } else { $scope.errors = data.errors; } }).error(function (data, status, headers, config) { $scope.errors = []; $scope.message = 'Unexpected Error while saving data!!'; }); $scope.isViewLoading = false; } }) .config(function ($locationProvider) { //default = 'false' $locationProvider.html5Mode(true); }); </script> }
Form Style:
<style> #content label { width: 150px; } #content input[type=submit] { margin-left: 154px; width: 120px; padding: 5px 15px; background: #ff6a00; border: 0 none; cursor: pointer; color: #fff; } .error { color: red; } .color-default { color: #000; } .color-red { color: red; } .color-green { color: green; } #content input.ng-dirty.ng-invalid { border: 1px solid red; background-color: rgb(255, 244, 244); } </style>
Output:
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 discus 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 define where application should be bootstrapped.
angular.module('myFormApp', [])
This is a module method which has two parameters.
- 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.
- The second parameter is an empty[] array in “angular.module(‘myFormApp’, [])” method. This array is the list of other dependent modules.
Next focus to Javascript Controller(CustomerController)
JavaScript Controller:
.controller('CustomerController', function ($scope) { //inner code });
Controller is a JavaScript function in AngularJS. The ng-controller directive in <div id=”content” ng-controller=”CustomerController”> defines the application controller.
$scope: Scope is an “object” that “binds together” to DOM element where controller relay. In simply scope connect between the HTML View & the JavaScript Controller.
HTML View:
<div ng-class="result">{{message}}</div>
JavaScript Controller:
.controller('CustomerController', function ($scope) { $scope.message = 'Show in view'; })
Let’s discuss about the validations of the form.
Validations:
Validations are 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 Custome Validation here.
Required Field Validator: To validate users empty input with AngularJS we used HTML5 attribute “required” or we can use ng-required=”true” .
<input type="email" ng-model="cust.CustEmail" name="email" required />
Validation Message:
<span class="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“.
<input type="text" ng-model="cust.CustName" name="cname" required ng-minlength="4" ng-maxlength="14" />
Validation Message:
<span class="error" ng-show="frmCustomer.$dirty && frmCustomer.cname.$error.minlength">Minimum length required is 5</span> <span class="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.
<span class="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 both the form and the input fields. They states are either 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 below method.
[HttpPost] public JsonResult CreateCustomer(Customer model) { if (ModelState.IsValid) { //Data save to database return Json(new { success = true }); } return Json(new { success = false, errors = ModelState.Keys.SelectMany(i => ModelState[i].Errors).Select(m => m.ErrorMessage).ToArray() }); }
Let’s modify our Javascript CustomerController.
angular.module('myFormApp', []). controller('CustomerController', function ($scope, $http) { $scope.cust = {}; $scope.message = ''; $scope.result = "color-default"; $scope.isViewLoading = false; //get called when user submits the form $scope.submitForm = function () { $scope.isViewLoading = true; console.log('Form is submitted with:', $scope.cust); //$http service that send or receive data from the remote server $http({ method: 'POST', url: '/Home/CreateCustomer', data: $scope.cust }).success(function (data, status, headers, config) { $scope.errors = []; if (data.success === true) { $scope.cust = {}; $scope.message = 'Form data Submitted!'; $scope.result = "color-green"; } else { $scope.errors = data.errors; } }).error(function (data, status, headers, config) { $scope.errors = []; $scope.message = 'Unexpected Error while saving data!!'; }); $scope.isViewLoading = false; } });
Let’s put a breakpoint on CreateCustomer() method in HomeController and run it, after submitting the form it’ll hits the breakpoint.
Fig: 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 are 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 Service is JavaScript functions to talk 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.
.config(function ($locationProvider) { $locationProvider.html5Mode(true); });
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.
$location.path(data.redirectUrl); $window.location.reload();
add base tag in head section(_Layout.cshtml) of master page/layout of application.
<base href="/">
Finally CustomerController(Javascript):
angular.module('myFormApp', []). controller('CustomerController', function ($scope, $http, $location, $window) { $scope.cust = {}; $scope.message = ''; $scope.result = "color-default"; $scope.isViewLoading = false; //get called when user submits the form $scope.submitForm = function () { $scope.isViewLoading = true; console.log('Form is submitted with:', $scope.cust); //$http service that send or receive data from the remote server $http({ method: 'POST', url: '/Home/CreateCustomer', data: $scope.cust }).success(function (data, status, headers, config) { $scope.errors = []; if (data.success === true) { $scope.cust = {}; $scope.message = 'Form data Submitted!'; $scope.result = "color-green"; $location.path(data.redirectUrl); $window.location.reload(); } else { $scope.errors = data.errors; } }).error(function (data, status, headers, config) { $scope.errors = []; $scope.message = 'Unexpected Error while saving data!!'; }); $scope.isViewLoading = false; } }) .config(function ($locationProvider) { //default = 'false' $locationProvider.html5Mode(true); });
Finally HomeController(MVC):
public class HomeController : Controller { // GET: Home public ActionResult Index() { return View(); } [HttpPost] public JsonResult CreateCustomer(Customer model) { if (ModelState.IsValid) { //Data save to database var RedirectUrl = Url.Action("About", "Home", new { area = "" }); return Json(new { success = true, redirectUrl = RedirectUrl }); } return Json(new { success = false, errors = ModelState.Keys.SelectMany(i => ModelState[i].Errors).Select(m => m.ErrorMessage).ToArray() }); } // GET: Home/About public ActionResult About() { return View(); } }
Output:
Source Code: I’ve uploaded the full source code to download/clone @github, Hope this will help 🙂
Points of Interest:
Next part we will create a sample application with AngularJS to perform CRUD operations with ASP.Net MVC
Syed Maftahur Rahman Sohel says:
Excellent
Shashangka Shekhar says:
Thanks
Sanjay says:
Great!!
Shashangka Shekhar says:
Thanks
Nathi says:
Awesome!! Thank you.
Shashangka Shekhar says:
(y)
Oliver says:
The download does not seem to be working
Shashangka Shekhar says:
Please get it from here, if there’s any problem:
https://github.com/ShashangkaShekhar
Ashu says:
Please explain the part of Customer Model and connectivity with database.
Also please explain how the data will be saved in the database
Shashangka Shekhar says:
Please follow the next part-
http://shashangka.com/2016/01/23/asp-net-mvc-5-with-angularjs-part-2/
gburgur says:
Should be everyone’s first MS MVC5 / AngularJS download. Self contained. Easy to follow without throwing in many “I know a bunch of stuff” by the author. Really had me understanding the subject matter in an hour of tracing it through over and over again. EXCELLENT. THANKS.
Ali says:
Hi, well your first example is not cool, as you added a script that is more than 100K, compared to the second one, plus, the section related to the normal jquery/javascript, you duplicated the function because you did not optimize your selector. I dont think you were successful in showing the benefit of Angular.
Add to that, the plug-ins that depend on JQuery are so rich, that most web application these days use it, so I dont think the size of JQuery is a factor as in real life applications, it is needed if you used Angular or not.
Question, Did you lose all the normal MVC validation when you used the Angular form?
home services in ghaziabad says:
Can I simply just say what a relief to discover an individual who actually knows what they are discussing online.
You definitely know how to bring an issue to light and make it important.
More people have to read this and understand this side of your story.
I was surprised that you’re not more popular since you surely possess
the gift.