Friday, April 24, 2015

Using AngularJS with MVC

This is a small example of combining the power of Web API with Angular JS. I have looked at many sites for a good post, but I could not find one which was precise and focused. In this post I intend to do just that.

The Project Objective:
In this example I will try to show a basic interaction between a UI created by the Angular JS and an MVC Web API service.

1) Create the Service Project:

Using VS 2013, create a WebApi project called MvcAngular.WebApi. I have called the solution MvcWithAngularSolution. The images below show can be used as a guideline.

Image 1

Image 2
2) Create a new class in Models folder and call it Pet:


     public class Pet
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string PetType { get; set; }
        public int Weight { get; set; }
    }

3) Delete the ValueController from the Controllers folder.

4) Create a new "Web API 2 Controller with read/write actions"  in the Controllers folder. Call it PetApiController.

Image 3

Image 4
5) To stay focus, we will not connect to a database. Instead we will create a list of pets and use that as our data source. Image 5 below shows the modifications needed to define the list and populate it.

Image 5 
6) We still need to do two more modification to the PetApiController. The original template uses an array of string. In this project we need to change the string type to Pet type. That will off course results in the logic change in bothe Get() and Get(int id) methods. So modify these methods to look like the once in Image 6 below:

Image 6

7) Before we move on, it is well worth to test the service. To do so, run the project in the development environment by hitting Ctrl-F5. Once the landing page appears add /api/PetApi for the first test and then /api/petApi/2 for the 2nd test. The first test should display all pets in the browser (see Image 7) while the 2nd test will display Id, Name, PetType and the Weight of pet with Id = 2 (see Image 8). Please do not proceed until both of these tests are working satisfactorily.

Image 7

Image 8

8) We are done with the back-end. Let's think about the UI. For this project, we need to have 2 views; a list view and a details view. Let add 2 actions to the Home MVC controller: PetsList() and PetById(). Image 9 below shows these actions (also not that I have changed the Index() action to be consistent with the new actions):



9) Now we need to create 2 views, one for each action; PetsList.cshtml and PetById.cshtml. Just right click inside each action and select "Add View". Accept all details and click the OK. Image 10 below shows the views created for these actions.

Image 10

10) At this stage we need to add 2 buttons to the landing page (and remove all unnecessary stuffs) and connect their click actions to the controller actions we just created. So change the index.cshtml in Views >  Home folder so that it looks like the following:

Image 11

11) At this stage if you run the application, you we should see screens similar to Image 12 - Image 14 below:

   
Image 12

Image 13
Image 14
12) Now we will start working on the Angular integration in to the application. To use Angular JS you need to use NuGet package manager console and install the "AngularJS.Core" in to the project. To do so, simply click Tools > NuGet Package Manager > Package Manager Console. The Package Manager Console will appear at the bottom of the bottom of the VS screen showing its prompt: PM>. Assuming you are connected to the internet, just type "Install-package AngularJS.Core". You can also specify the name of your target project. See Image below:

Image 15
13) You also need to insert the angular directive in the html tag in the _layout.cshtml. The basic directive is "ng-app", this will initialize the Angular JS library so that your application can execute other Angular command. No need to mention that we need to reference the Angular.js in the header of the page in order to enable the browser to find it. With these 2 mods, the _Layout.cshtml looks like this (Image 16):

Image 16

14) At this stage we need to ensure that AngularJS is installed and configure correctly and it is actually working. The test is simple: we will see if a basic angular expression such as {{ 2 + 3 }} is handled correctly. You just need to add this one of your views, if the view shows "5" the you are good, if not need to go back and see what got messed up! Image 17 highlights the test and Image 18 shows the test result.

Image 17
Image 18
15) Now it is time to create the Angular Controller which is simply a javascript file. In order to keep javascript files organized, it is good practice to create a subfolder inside the Scripts folder. Let's call this new folder "app". Let's add a JavaScript file as a new item to this folder and name it as "PetJsController.js".  Add the following to this new file:

Image 19
As you can see the controller is placed inside a Javascript Closure. This is an Immediate Function and will be run only once. Read about the JavaScript Closures here. The controller is inside an Angular Module named PetsApp. Modules are containers for different parts of an angular application. Read about Angular Modules here. The Controller has 3 methods, GetAllPets(), GetPetById and ClearScreen. We will use these methods to access the WebApi service. The service will be accessed by using the $http Angular Service. $http is a core Angular service that communicate with http based services via XmlHttpRequest object. Read more about $http here. $scope offers an execution context for the methods of the Controller. Read more about $scopes here and Controllers here.

16) Now it is time to modify the view files so that they can use the controller module. The first step is to tell the views to use the PetsApp module. This is simple done by modifying the ng-app directive in the html tag i _Layout.cshtml. You need to change the directive from "ng-app" to "ng-app='PetsApp'". No need to say that you also need to add a reference to the controller file in "app" subfolder. See Image 20 below.

Image 20

17) We need to modify both the PetsList.cshtml and PetById.cshtml views as shown in Image 21 below.

Image 21

18) Now it is time to run the application and see if it works. You should have the following series of screens.






Conclusion:

The UX/UI is not great at all. But the purpose of this post was not to show you how to create a great User Interface. The purpose was to focus on getting the AngularJS to work with the WebApi. And this is exactly what this solution does. Basically we passed the Web Service URL to the AngularJS $http service in the AngularJS controller.


No comments: