Introducing Angular js into Asp.Net MVC application.

Creating basic example in AngularJS in Asp.Net MVC. Basic understanding of angular patterns and variables.

 Angular   
 

Posted: July 19, 2016. | By: mustafa

Lets start this article with defining what is AngularJS. AngularJS is a javaScript framework designed for SPA applications. It extends html DOM elements with additional attributes and makes it more responsive. It is based MVVM design pattern (Model View View Model).

AngularJSBasicIntegrationWithAsp.Net.png, Angular, javascript, AngularJS, Asp.Net,
We will be adding angular in Asp.Net Mvc project building a simple SPA application.

Introducing AngularJS

Installing Angular using Nuget in Package Manager Console.

PM> install-package angularjs

Once installed, we add a reference to it in our html view. AngularJS extends HTML attributes with Directives, and binds data to HTML with Expressions.

I will show today a basic example of creating a angular app and using it to add userprofile containing firstname, lastname, mobile & address.
In MVC create a basic controller and add index view, add script tag referencing angular.js in our view.

Next we are going to add app.js containing defintion for module, user.js file defining controller.

A Module in AngularJS is like a container. It can contain different parts of your application like – Controllers, Services, Filters, and Directives etc.

var app = angular.module('AngularApp', []);

Notice the empty array parameter. If we do not have any resources to pass, we have to pass an empty array. Or it may result in undesired results.

Now add basic angular controller in user.js.
app.controller('User', function ($scope, $http, $filter) {

    });

$scope that was passed into the controller was actually instantiated and passed by Angular. Those familiar with constructor injection will realize that Angular actually injected the $scope without us having to worry about it. This is the uniqueness and strength of Angular.

All of the JavaScript files are located in the AngularJS folder, while using angular we must be familiar with the patterns used in the JavaScript. All functions are defined using constructs of a JavaScript Framework(is well-structured JavaScript code).

To hookup the Module specify ng-app attribute in razor view in  container div. The ng-app directive defines an AngularJS application. 

<div ng-app="AngularApp">

Then, inside declare another div containing ng-controller attribute to define scope of controller.

<div ng-controller="User">

Next we are going to define scope inside our angular controller. What is $scope, It is used for sharing data between our controller and a view.
 	$scope.firstName = "";
        $scope.lastName = "";
        $scope.mobile = "";
        $scope.address = "";
 
How do we include scope variable in our html.
 
  1. AngularJS expressions are written inside double braces: {{ expression }}.
  2. ng-bind directive is used to bind innerHTML of html element.
  3. ng-model directive binds the value of the input field to scope variable this is a two way data binding.

 

Directives in AngularJS are special keywords that have built in functionality. They can apply to elements attributes, classes or comments.

In our case, we are going to use ng-model to bind input boxes.

<div class="form-group">
            <label class="control-label col-md-2">First Name</label>
            <div class="col-md-4">
                <input type="text" class="form-control" placeholder="First Name" ng-model="firstName" />
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-md-2">Last Name</label>
            <div class="col-md-4">
                <input type="text" class="form-control" placeholder="Last Name" ng-model="lastName" />
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-md-2">Mobile</label>
            <div class="col-md-4">
                <input type="text" class="form-control" placeholder="Mobile" ng-model="mobile" />
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-md-2">Address</label>
            <div class="col-md-4">
                <textarea class="form-control" placeholder="Address" ng-model="address"></textarea>
            </div>
        </div>
    <div class="form-group">
            <div class="col-md-offset-6 col-md-6">
                <input type="button" value="Add User" ng-click="AddUser()" class="btn btn-primary" />
            </div>
        </div>
 

We have a basic controller lets add a method returning JsonResult.

public JsonResult AddUserProfile(UserProfile userProfile)
        {
            TestWebContext dbContext = new TestWebContext();
            dbContext.UserProfile.Add(userProfile);
            dbContext.SaveChanges();
            return Json(new { Valid = true });
        }

To consume this mehtod in our angular controller we are going to add a function to make ajax call using angular $http.post().

$scope.AddUser = function () {
            var data = {
                "FirstName": $scope.firstName,
                "LastName": $scope.lastName,
                "MobileAlias": $scope.mobile,
                "Address": $scope.address
            }
            var promise = $http.post
                    ("/Basic/AddUserProfile", data);
            promise.success(function (response) {
                if (response.Valid) {
                    alert("User profile added successfully.");
                }
            }).error(function (ex) {
                alert("Error " + ex);
            });
        }
 
$http is a wrapper for http functions getting injected into the controller. We will use this to retrieve the Promise return by the $http.get() & $http.post(). A promise is like a delegate or callback used while making AJAX calls.

In this method we are calling the AddUserProfile() method defined in our BasicController. Once the Promise completes successfully, we get the JSON result from the server.

On getting success we show the alert message 'Profile added successfully'. Here is the complete user.js file.
(function (app) {
    'use strict';

    app.controller('User', function ($scope, $http, $filter) {
        $scope.firstName = "";
        $scope.lastName = "";
        $scope.mobile = "";
        $scope.address = "";

        $scope.AddUser = function () {
            var data = {
                "FirstName": $scope.firstName,
                "LastName": $scope.lastName,
                "MobileAlias": $scope.mobile,
                "Address": $scope.address
            }
            var promise = $http.post
                    ("/Basic/AddUserProfile", data);
            promise.success(function (response) {
                if (response.Valid) {
                    alert("User profile added successfully.");
                }
            }).error(function (ex) {
                alert("Error " + ex);
            });
        }
    });
})(app);

related posts

Back to top