Using AngularJS with .NET MVC 5

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

In Model, create a class Category:

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.

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

The controller will automatically create the API methods.

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

In this controller, create ActionResult Index.

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

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

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

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

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

/// <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.,

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:

<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!

posted on   大西瓜3721  阅读(210)  评论(0编辑  收藏  举报

编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
历史上的今天:
2015-05-16 由点击页面其它地方隐藏div所想到的jQuery的delegate
2015-05-16 jquery如何选择带有多个class的元素

导航

点击右上角即可分享
微信分享提示