Click here to Skip to main content
15,892,927 members
Articles / AngularJs
Tip/Trick

Using AngularJS with .NET MVC 5

Rate me:
Please Sign up or sign in to vote.
4.04/5 (9 votes)
13 Jun 2015CPOL2 min read 23.4K   11   12
Using AngularJS with .NET MVC application

Introduction

This tip shows the use of AngularJS with .NET MVC5 application. Here is a simple step-by-step example for the use of AngularJs with .NET MVC application.

Background

While searching for an article for the use of AngularJS with .NET MVC technology, the search always shows AngularJS and explains its MVC methodology. But there is nothing much on the topic.

Using the Code - Step by Step

Create a new project and select MVC template and check Web API as well and select OK.

Image 1

In Model, create a class Category:

C#
public class Category
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
    }

On Controller folder, add New Controller and select Web API2 Controller.

Image 2

And then, select Category as Model Class and in controller name, write CategoriesApiController as shown in the following image:

Image 3

The controller will automatically create the API methods.

Now, create a new empty Controller and name it CategoriesController.

Image 4

In this controller, create ActionResult Index.

C#
public class CategoriesController : Controller
    {
        private ApplicationDbContext db = new ApplicationDbContext();
        // GET: Categories
        public ActionResult Index()
        {
            return View();
        }     
    }

Now, it's time to write AngularJs code before creating the index view. Use Manage NuGet package and install AngularJS.

Now, right click Script folder -> Add -> New Folder and name folder Category.

Image 5

In Category folder, right-click and Add new item JavaScript File and name the file categoryModule.js and write the following code in it:

JavaScript
/// <reference path="../angular.js" />
var app1;
(function () {
// this line initialize the name of module
    app1 = angular.module("catModule", []);
})();

In Category folder, create a new JavaScript file named “service.js”and add the following code in it. In this file, we have created JavaScript methods to call methods defined in WebAPI controller.

JavaScript
/// <reference path="../angular.js" />
/// <reference path="categoryModule.js" />
// top two line include the reference to angular.js file and categoryModule.js file 
// we created in the above step
app1.service("catService", function ($http) {
    // get all category records
    this.getCategories = function () {   return $http.get("/api/CategoriesAPI");    }
    // get single record
    this.get = function (id) {       return $http.get("/api/CategoriesAPI/" + id);    }
    // create new record
    this.post = function(Category)
    {
        var request = $http({
            method: "post",
            url: "/api/CategoriesAPI",
            data: Category
        });
        return request;
    }
    this.delete = function (Cat) {   
        var request = $http({
            method: "delete",
            url: "/api/CategoriesAPI/" + Cat
    });
        return request;
    }
});

Now create another JavaScript file in category folder, name it “CategoryController.js” and paste the following code in it.

JavaScript
/// <reference path="../angular.js" />
/// <reference path="categoryModule.js" />
app1.controller("catController", function ($scope, catService) {
    $scope.IsNewRecord = 1;   
    loadRecords();
// loading all records
    function loadRecords() {
        promiseGet = catService.getCategories();
        promiseGet.then(function (p1) {
            $scope.Categories = p1.data
        },
        function (errorP1) {
            console.log("Error in getting category " + errorP1);
        });
    }
// get single record
    $scope.get = function (Cat) {
        var promiseGetSingle = catService.get(Cat.Id);
        promiseGetSingle.then(function (p1) {
            var res = p1.data;
            $scope.Id = res.Id;
            $scope.Name = res.Name;
        },
        function (errorp1) {
            console.log("Error in code " + errorp1);
        } );
    }
// save record
    $scope.save = function () {
        var Category = {
            CatId: $scope.CatId,
            Name: $scope.CategoryName
        };
        if($scope.IsNewRecord === 1){
            var promisePost = catService.post(Category);
            promisePost.then(function(p1){
                $scope.CatId = p1.data.CatId;
                $scope.CategoryName = "";
                loadRecords();
            },function(err){console.log('Error '+ err);
            });
        }else{
            var promisePut = catService.put($scope.CatId,Name);
            promisePut.then(function(p1){
                $scope.Message = "Successfully Updated";               
                loadRecords();
            },function(err){       console.log('Error ' + err);           });
        }    }
// Delete record
    $scope.delete = function (id) {       
        var promiseDelete = catService.delete(id);
        promiseDelete.then(function (p1) {
            $scope.Message = "Record Deleted successfully";
            loadRecords();
        },function(err){           console.log("Error "+ err);    });
    }});

Now we have written all the JavaScript we needed. Now go to CategoryController created earlier, i.e.,

C#
public ActionResult Index()
{
    return View();
}

Right click on index() and click Add View and add empty view. Add the following code in the index.cshtml file:

HTML
<div ng-app="catModule" >
    @{        ViewBag.Title = "Index";    }
    <div ng-controller="catController">
        <h2>Categories</h2>       
        <table class="table">
            <thead>
                <tr>
                    <th><span>Id</span></th>
                    <th><span>Category</span></th>
                </tr>
            </thead>
            <tbody ng-repeat="Cat in Categories">
                <tr>
                    <td><span> {{Cat.Id}}</span></td>
                    <td><span>{{Cat.Name}}</span></td>
                    <td><span><input type="button" 
                    class="btn btn-danger" value="Delete" 
                    ng-click="delete(Cat.Id)" /> </span></td>
                </tr>
            </tbody>
        </table>
        <form ng-submit="">
            Category <input type="text" ng-model="CategoryName" />
            <input type="submit" value="Submit" ng-click="save()" />
        </form>
        <script src="~/Scripts/angular.js"></script>
        <script src="~/Scripts/angular-route.js"></script>
        <script src="~/Scripts/category/categoryModule.js"></script>
        <script src="~/Scripts/category/Service.js"></script>
        <script src="~/Scripts/category/CategoryController.js"></script>
    </div>
</div>

Run the application. Navigate to /Category... Now add Categories and delete categories. Enjoy!

Image 6

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Pakistan Pakistan
I love to work with .Net MVC.

Comments and Discussions

 
QuestionReference Path Pin
garybee16-Jun-15 2:20
garybee16-Jun-15 2:20 
AnswerRe: Reference Path Pin
Abid Rashid16-Jun-15 23:23
Abid Rashid16-Jun-15 23:23 
QuestionAnjularJS ? Pin
Michael Gledhill15-Jun-15 23:20
Michael Gledhill15-Jun-15 23:20 
AnswerRe: AnjularJS ? Pin
Abid Rashid16-Jun-15 0:30
Abid Rashid16-Jun-15 0:30 
GeneralRe: AnjularJS ? Pin
Michael Gledhill16-Jun-15 2:31
Michael Gledhill16-Jun-15 2:31 
GeneralRe: AnjularJS ? Pin
Abid Rashid16-Jun-15 23:26
Abid Rashid16-Jun-15 23:26 
GeneralRe: AnjularJS ? Pin
Michael Gledhill16-Jun-15 23:49
Michael Gledhill16-Jun-15 23:49 
(He doesn't get it, does he..?)

It's called AngularJS, not AnjularJS !

It would be worth editing your article, and changing the spelling mistake in the title...
GeneralRe: AnjularJS ? Pin
Abid Rashid18-Jun-15 18:55
Abid Rashid18-Jun-15 18:55 
QuestionAfter saving list does not load Pin
Deepesh Kapadia14-Jun-15 1:00
Deepesh Kapadia14-Jun-15 1:00 
AnswerRe: After saving list does not load Pin
Deepesh Kapadia14-Jun-15 1:14
Deepesh Kapadia14-Jun-15 1:14 
GeneralRe: After saving list does not load Pin
Abid Rashid14-Jun-15 2:44
Abid Rashid14-Jun-15 2:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.