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:

Hide   Copy Code

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.

Hide   Copy Code

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:

Hide   Copy Code

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

Hide   Copy Code

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

Hide   Shrink    Copy Code

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

Hide   Copy Code

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:

Hide   Shrink    Copy Code

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

时间: 2024-10-06 04:34:08

Using AngularJS with .NET MVC 5的相关文章

ABP 教程文档 1-1 手把手引进门之 AngularJs, ASP.NET MVC, Web API 和 EntityFramework(官方教程翻译版 版本3.2.5)含学习资料

本文是ABP官方文档翻译版,翻译基于 3.2.5 版本 转载请注明出处:http://www.cnblogs.com/yabu007/  谢谢 官方文档分四部分 一. 教程文档 二.ABP 框架 三.zero 模块 四.其他(中文翻译资源) 本篇是第一部分的第一篇. 第一部分分三篇 1-1 手把手引进门 1-2 进阶 1-3 杂项 (相关理论知识) 第一篇含两个步骤. 1-1-1 ASP.NET Core & Entity Framework Core 后端(内核)含两篇 ( 第一篇链接    

AngularJS中的MVC模式

MVC根据逻辑关系,把前端项目的代码分为三个层次 model:模型,就是业务数据,前端项目中就是JS变量. view:视图,就是业务数据在用户面前的展现,前端项目中就是HTML. controller:控制器,负责业务数据的增删改查,前段项目中就是function. AngularJS的四大特性:MVC设计模式.双向数据绑定.依赖注入.模块化设计

[Angularjs]asp.net mvc+angularjs+web api单页应用

小分享:我有几张阿里云优惠券,用券购买或者升级阿里云相应产品最多可以优惠五折!领券地址:https://promotion.aliyun.com/ntms/act/ambassador/sharetouser.html?userCode=ohmepe03 写在前面 最近的工作一直在弄一些h5的单页应用,然后嵌入到app的webview中.之前一直在用angularjs+html+ashx的一套东西.实在是玩腻了.然后就尝试通过asp.net mvc的方式构建单页应用.用到的技术angularjs

案例:1 Ionic Framework+AngularJS+ASP.NET MVC WebApi Jsonp 移动开发

落叶的庭院扫的一干二净之后,还要轻轻把树摇一下,抖落几片叶子,这才是Wabi Sabi的境界. 介绍:Ionic是移动框架,angularjs这就不用说了,ASP.Net MVC WebApi提供数据源,开放数据接口 快乐学习 Ionic Framework+PhoneGap 手册1-1{创建APP项目}{点击查看} 快乐学习 Ionic Framework+PhoneGap 手册1-2{介绍Header,Content,Footer的使用}{点击查看} 快乐学习 Ionic Framework

AngularJS+ASP.NET MVC+SignalR实现消息推送

原文:http://www.mincoder.com/article/4565.shtml 背景 OA管理系统中,员工提交申请单,消息实时通知到相关人员及时进行审批,审批之后将结果推送给用户. 技术选择 最开始发现的是firebase,于是很兴奋的开始倒腾起来.firebase用 起来倒是简单:引用一个js即可,按官网上的教程很快便应用到了项目中.第二天打开项目发现推送功能不好使了,这是为何?最后发现firebase官网打 不开了...难道firebase被google收了也会被天朝给墙掉?也许

AngularJs 特性 之 MVC

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="../../jslib/angular.min-1.5.8.js"></script> <script src="HelloAngular_MVC.js"></script> </head> <body&

[Angularjs]asp.net mvc+angularjs+web api单页应用之CRUD操作

写在前面 前篇文章整理了angularjs学习目录,有园子里的朋友问我要这方面的demo,周末也没什么事,就在之前的单页应用的demo上面添加了增删改查的操作.代码比较简单,这里只列举比较重要的代码片段.完整的代码将在文章下面提供链接. demo 数据来源通过webapi的方式提供.获取对产品的查询,分页,增加商品,删除,修改等操作. webapi using Newtonsoft.Json; using System; using System.Collections.Generic; usi

AngularJs MVC 详解

为什么在前端也需要MVC 1.代码规模越来越大,切分职责是大势所趋 2.为了复用 3.为了后期维护方便 MVC的目的是为了模块化和复用 前端实现MVC的困难 1.操作DOM必须等整个页面加载完 2.多个js如果出现依赖,需要程序员自己解决 3.js的原型继承 Controller 需求:有一些功能,在各个控制器中都会用到,怎么办? 1 <!DOCTYPE html> 2 <html lang="en" ng-app="myApp"> 3 &l

ASP.NET MVC和EF集成AngularJS开发

参考资料: 如何在ASP.NET MVC和EF中使用AngularJS AngularJS+ASP.NET MVC+SignalR实现消息推送 [AngularJs + ASP.NET MVC]使用AntularJs快速建立ASP.NET MVC SPA網站