Creating Unit Tests for ASP.NET MVC Controllers

In this blog post, we will learn to write unit tests for various MVC controller’s behaviors, such as view’s return types, redirecting to different actions etc. Specifically, we’ll cover writing Unit Tests for:

  1. ViewData of the Controller
  2. TempData of the Controller
  3. ViewBag of the Controller
  4. View of the Controller

Let’s get started!

Creating the MVC Project under Test

Let us go ahead and create a MVC project under Test. To keep things simpler, I have selected ”No Authentication” for the project. In this example we are going to write unit tests for the HomeController. The HomeController contains two action methods:

  1. Index
  2. Details

We are going to write tests for these actions. The HomeController contains code as shown here:

Read full article on the Infragistics Blog

Exploring Angular’s “Controller as” Syntax and the vm Variable

Read full article on the Infragistics blog

Often, I hear developers ask “What is the ‘controller as’ syntax and how it is different from the $scope object approach of controller creation?” In this post we will learn about controller as syntax and compare it with the $scope object approach of controller creation.

In AngularJS 1.2, the “controller as” syntax was introduced, and made controller code creation more readable. Let’s see both approaches in action below:

Creating a controller using the $scope object

Usually we create a controller using the $scope object as shown in the listing below:

image

Above we are creating the AddController with three variables and one behaviour, using the $scope object controller and view, which talk to each other. The $scope object is used to pass data and behaviour to the view. It glues the view and controller together.

Essentially the $scope object performs the following tasks:

  1. Pass data from the controller to the view
  2. Pass behaviour from the controller to the view
  3. Glues the controller and view together
  4. The $scope object gets modified when a view changes and a view gets modified when the properties of the $scope object change

We attach properties to a $scope object to pass data and behaviour to the view. Before using the $scope object in the controller, we need to pass it in the controller function as dependencies.

Using the “controller as” syntax and vm

We can rewrite the above controller using the controller as syntax and the vm variable as shown in the listing below:

image

Read full article on the Infragistics blog

How to share data between controllers in AngularJS

 

In my AngularJS classes, I often get asked, “How do I share data between the controllers in AngularJS?” On the Internet, there are many solutions suggested. However, I prefer to share data using the Shared Data Service method, and that’s what we’re going to explore in this post.

To start with, let’s suppose that we want to share a Product object between the controllers. Here I have created an AngularJS service named SharedDataService as shown in the snippet below:

Read full article on the Infragistics blog

21 points cheat sheet on AngularJS controller and the $scope object

This blog post is a 21 points cheat sheet on the AngularJS controller and the $scope object. These points can be used a quick notes while working with two important components of Angular app controller and the $scope object Notes on $scope object $scope is a glue between the view and the controller. It connects controller with the view. image

  1. $scope serve as the glue between controller and the view
  2. The $scope is the connection between the HTML and the view
  3. View and the model both have access of $scope
  4. In context of MVC , $scope can be seen as ViewModel
  5. $scope provides execution context for the DOM and the expression
  6. $scope provides an execution context in which DOM element is bound
  7. $scope are the source of the truth
  8. $scope gets modified when View changes and the view gets modified when $scope changes its value
  9. The $scope object is plain JavaScript object. We can add and remove property as required
  10. $scope holds data and functions from controller that should be displayed and get executed in view
  11. The $rootScope is eventual parent of all the $scope
  12. $rootScope is top most scope in on DOM element with ng-app directive
  13. In angular all the $scope are created with prototypal inheritance
  14. $scope has access to their parent scope
  15. $scope contains data and the functionality to be used to render the view
  16. For each controller creation and new $scope gets created
  17. It is ideal to contain the application logic in the controller and the data in the $scope of the controller.
  18. When $scope object is not needed in the view, scope will be cleaned up and destroyed
  19. Directives does not have their own scope but with some exceptions ng-controller and ng-repeat
  20. When angular starts running all the $scope are attached to the view
  21. $scope pass data and behavior to the view

Example: Adding property to $rootScope To add a property to $rootScope directly, pass $rootScope as parameter to the controller as shown below. However it is not advisable to add properties to $rootScope directly.

var myApp = angular.module('myApp', []);
myApp.controller('RootController', ['$rootScope', function ($rootScope) {

    $rootScope.name = "dj";

}]);

On the DOM added property of $rootScope can be rendered in the expression as shown below,

<div ng-controller="RootController">
<h1><strong>{{</strong>name<strong>}}</strong></h1>

</div>

Other way you can add property to the $rootScope object directly using the run method on the application module.

angular.module('myApp', [])
      .run(function ($rootScope) {
          $rootScope.name = &amp;quot;World&amp;quot;;
      });

To use this you don’t need controller to attach with the View and can be used in the application as shown below,

   <div ng-app="myApp">
        Hello {{name}}
    </div>


Notes on the controller

Controller adds behaviour and data to the $scope object. It gets created on the view using this ng-controller directive. Each controller has its own $scope object. image

  1. It’s a JavaScript constructor function that is used to augment the $scope object
  2. Controller takes $scope as parameter and attach data and behavior to this
  3. Controller is attached to DOM using the ng-controller directive
  4. Each controller has its own child $scope
  5. Controller set up the initial state of the $scope object
  6. Controller adds behavior to the $scope object
  7. Do not use Controller to manipulate DOM : It should only contain the business Login not the DOM manipulation
  8. Do not use controller to format the input
  9. Do not use controller to filter the output
  10. Do not use controller to share the code across the controller
  11. Never create the service instance inside the controller
  12. A Controller should mainly contain a simple business logic
  13. It should not try to do many things
  14. All the common functionality should go the service and the later service can be injected to the controller via dependencies
  15. Controller name starts with the capital letter and ends with the Controller
  16. Whenever new controller gets created on the page, angular pass a $scope object to it.
  17. Custom actions to be called from the view can be created as behavior of function in the controller augmenting to the $scope object
  18. Controller can be attached to different level of DOM hierarchy, hence its create hierarchy of the $scope.
  19. $scope in child controller can access and override data and behavior attached to $scope of the parent controller.
  20. Other directives or services to be used in the controller must be passed as parameter in the controller function constructor
  21. Controller should provide data and business logic to a particular View

Example: Creating a simple controller Let us create a simple controller with two functions as behavior and one data. Functions are either adding or subtracting 1 from the counter attached as property to $scope object.

var myApp = angular.module('myApp', []);
myApp.controller('mycontroller', ['$scope', function ($scope) {

    $scope.counter =0;
    $scope.add = function () { $scope.counter += 1;}
    $scope.sub = function () { $scope.counter -= 1; }
}]);

On the DOM controller can be used as shown below,


  <div ng-controller="mycontroller">
            <h1>{{counter}}</h1>
            <button class="btn btn-info" ng-click="add()">+</button>
            <button class="btn btn-danger" ng-click="sub()">-</button>
        </div>


When you use controller to another DOM element, a new instance of controller will get created.


<div class="container">

        <div ng-controller="ParentController">
            <h2>{{age}}</h2>
            <div ng-controller="ChildController">
                <h1>{{name}}</h1>
                <h2>{{age}}</h2>
                <h3>{{grade}}</h3>
            </div>
        </div>


On running the application you will find that both the div has different values for the $scope data. Example: $scope inheritance Let us create a module with two controller ParentControler and ChildController. As you see ChildController is overriding age property on the $scope object.

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

myApp.controller('ParentController', ['$scope', function ($scope) {

    $scope.name = "dj";
    $scope.age = 32;

}]);
myApp.controller('ChildController', ['$scope', function ($scope) {

    $scope.age = 22;
    $scope.grade = &amp;quot;A+&amp;quot;;

}]);

In the view we have created ChildController inside the ParentController div. In the ChildController $scope, there is no property called name. So angular will traverse to the ParentController to find the value of the name property. Also you can notice that age property is overridden in the ChildController, so the div attached with the ChildController will render overridden value of the age property.


<div class="container">

        <div ng-controller="ParentController">
            <h2>{{age}}</h2>
            <div ng-controller="ChildController">
                <h1>{{name}}</h1>
                <h2>{{age}}</h2>
                <h3>{{grade}}</h3>
            </div>
        </div>


I hope, these 21 points about the $scope object and the controller should help you in working with AngularJS. Thanks for reading.

Day #1: Learn ASP.NET MVC 5- Adding Controller

 

After long time, I am back to web development. At current web development paradigm, ASP.NET MVC framework is one of the most popular and heavily used web development framework. Seeing popularity and usefulness of ASP.NET MVC, I have decided to write easy to go blog series on this. In this blog post series, each day I will share my learning in form of blog posts.

In day 1, let us learn about Controller. Very first in simpler words,

“Controller does all the actions in MVC. It handles user interactions or inputs. It passes users’ data to Model and selects a View to render on UI”

image

In more coding terms, Controller can be define as below,

  1. Controller is a class
  2. It contains one or more methods called Actions
  3. An Action can return simple string or a selected View to UI
  4. Action takes all browser requests or user inputs
  5. It retrieves data from Model
  6. It selects View to be rendered on UI

You can add a controller by right clicking on Controllers folder in solution explorer. In context menu select Add->Controller. There are different types of Controller templates are available to add. Let us go ahead and select MVC 5 Controller- Empty template to add controller.

image

Next give name to Controller. I am giving name as ProductController.

image

In solution explorer, you will notice In Controller folder, ProductController.cs file being added and in Views folder, there is subfolder Product being added.

image

Next let us go ahead and remove default code created and following two actions. First Action is Index (It is default) action. Index action does not take any input parameter. Second Action added is Welcome. It takes two input parameters id and name.

 


public class ProductController : Controller
{
//
// GET: /Product/
public string Index()
{
return "this is default action";
}

public string Welcome(string name, int id)
{
return "this is welcome action" + name + "with id " + id;
}
}

Following points are worth noticing about ProductController.

  1. ProductController class extends Controller class
  2. Actions are created as methods.
  3. In this case Actions are returning string.
  4. Actions can return other types as well. We will discuss them in further posts.
  5. Actions can take zero or more input parameter.

Let us go ahead and run application. Default action of Product controller is index. On navigating Product Controller, Index action will be called. In this case Index action is returning a string.

clip_image002

We have put one more action Welcome in Product controller. This takes two input parameters Id and name. You can call Welcome action as below. We are passing two input parameters as query string.

image

Better approach to pass input parameters are as Route Data than query string. Id is default input parameter. So instead of passing id as query string, you can pass it as route data as well.

clip_image002[6]

You can find default route and parameters in RouteConfig.cs.

 

clip_image003

 

In above code as you see default controller is Home, default action is Index and default optional parameter is id. If you want to pass other input parameters as route option, you can very much do that by adding more routes.

clip_image005

We have added a route with name and id as parameter. On running application, now you can pass name and id as route option.

clip_image007

This is the basic of working with Controllers in MVC. In further posts we will get into deeper concepts of Controllers. I hope you find this post useful. Thanks for reading.