ASP.NET MVC-5 with AngularJS Part – 1

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).

AngularJS_logo

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: ) 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”.

NGvJS

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-

    First Name:  
Last Name:
Result: {{fname +' '+ lname}}

JQuery-

    First Name:  
Last Name:
Result:

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

ang-1

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

ang-2

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

Fig: 1.2

ang-3

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

ang-4

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

ang-5

Code in Index.html


    First Name:  
Last Name:
Result: {{fname +' '+ lname}}

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:

ang-6

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

ang-7

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

ang-8

Let’s goto [Views > Shared > _layout.cshtml] and add Module, this is the start point where application should be bootstrapped.


                        

Form:

loading...
{{message}}

Customer name is Required Minimum length required is 5 Minimum length required is 15
EmailId is Required! Invalid EmailId!

Script:

 JavaScript{
    
    
    
    
}

Form Style:


Output:

ang-10

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.

  1. The first parameter is module name, that reference to “myFormApp” module in 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 Javascript Controller(CustomerController)

JavaScript Controller:

.controller('CustomerController', function ($scope) {
//inner code
});

Controller is a JavaScript function in AngularJS. The ng-controller directive in

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

$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:

{{message}}

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” .

Validation Message:

EmailId is Required!

Range Validator: To validate user input by range with AngularJS we used HTML5 attribute “ng-minlength, ng-maxlength“.

Validation Message:

Minimum length required is 5

Minimum length required is 15

Type Validation: To validate the email type we can use this in AngularJS.

Invalid EmailId!

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

ang-11

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

Output: 

ang-10

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.

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: 

ang-10

ang-13

Source Code: I’ve uploaded the full source code to download/clone , 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

Author:

Since March 2011, have 8+ years of professional experience on software development, currently working as Senior Software Engineer at s3 Innovate Pte Ltd.

13 thoughts on “ASP.NET MVC-5 with AngularJS Part – 1”

Leave a Reply