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!

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

  1. [译]ABP框架使用AngularJs,ASP.NET MVC,Web API和EntityFramework构建N层架构的SPA应用程序

    本文转自:http://www.skcode.cn/archives/281 本文演示ABP框架如何使用AngularJs,ASP.NET MVC,Web API 和EntityFramework构建 ...

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

    原文:AngularJS+ASP.NET MVC+SignalR实现消息推送 背景 OA管理系统中,员工提交申请单,消息实时通知到相关人员及时进行审批,审批之后将结果推送给用户. 技术选择 最开始发现 ...

  3. AngularJs + ASP.NET MVC

    [AngularJs + ASP.NET MVC]使用AntularJs快速建立ASP.NET MVC SPA網站 這幾天接觸到了AngularJs的美麗,讓饅頭有點躍躍欲試使用AngularJs來做 ...

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

    本文是ABP官方文档翻译版,翻译基于 3.2.5 版本 转载请注明出处:http://www.cnblogs.com/yabu007/  谢谢 官方文档分四部分 一. 教程文档 二.ABP 框架 三. ...

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

    写在前面 最近的工作一直在弄一些h5的单页应用,然后嵌入到app的webview中.之前一直在用angularjs+html+ashx的一套东西.实在是玩腻了.然后就尝试通过asp.net mvc的方 ...

  6. AngularJS中的MVC模式

    MVC根据逻辑关系,把前端项目的代码分为三个层次 model:模型,就是业务数据,前端项目中就是JS变量. view:视图,就是业务数据在用户面前的展现,前端项目中就是HTML. controller ...

  7. angularJS中的MVC思想?

    mvc 思想: 将应用程序的组成,划分为三个部分:model , controller 和 view ; - 控制器的作用是用来初始化模型用的: - 模型就是用于存储数据的: - 视图是展示数据的: ...

  8. AngularJS学习之MVC模式

    AngularJS是谷歌开发维护的前端MVC框架,克服了HTML在构建应用上的不足,从而降低了开发的成本. 在学习AngularJS之前,有必要和之前学过的jQuery进行对比.jQuery是java ...

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

    落叶的庭院扫的一干二净之后,还要轻轻把树摇一下,抖落几片叶子,这才是Wabi Sabi的境界. 介绍:Ionic是移动框架,angularjs这就不用说了,ASP.Net MVC WebApi提供数据 ...

随机推荐

  1. 解决.net定时器在iis7上不执行问题

    今天第一次在博客园发帖,以前一直在潜水,在这里也是学了不少东西.感谢各位园友 废话不多说,这也是我工作中遇到的问题: protected void Application_Start(object s ...

  2. 在一个工程管理多个应用-b

    Demo:http://download.csdn.net/detail/u012881779/9166527 本文的产生是因产品经理提出的特殊需求: 一个针对多所学校的应用,对不同学校需要分别使用一 ...

  3. 【贪心】 BZOJ 3252:攻略

    3252: 攻略 Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 261  Solved: 90[Submit][Status][Discuss] De ...

  4. 【高斯消元】BZOJ 1770: [Usaco2009 Nov]lights 燈

    Description 貝希和她的閨密們在她們的牛棚中玩遊戲.但是天不從人願,突然,牛棚的電源跳閘了,所有的燈都被關閉了.貝希是一個很膽小的女生,在伸手不見拇指的無盡的黑暗中,她感到驚恐,痛苦與絕望. ...

  5. 如何将word中上下两行文字对齐?

    一.问题来源及描述 本科毕设的时候积累的问题,整理如下. 红头文件下面的署名,上下要对齐. 二.解决办法 经验证,第一次拉标尺要把标尺放在第一行的光标处,为了换行后,再次enter,tab后到与上一行 ...

  6. [转载]easyui datagrid 时间格化(JS 日期时间本地化显示)

    easyui datagrid 日期时间显示不正常,后台java 类型为 DATE 经过JSON工具一转化传到前台来就是这样,不便 于是想格式化一下, 格式化代码 如下: [javascript] v ...

  7. Unity3D开发之查找面板上某个脚本(包括Missing)

    原地址:http://blog.csdn.net/lihandsome/article/details/24265411 有时候我们需要知道某个脚本在场景上面哪里用到,或者那个脚本被删除了但又没有把相 ...

  8. java中dao层和service层的区别是什么?

    首先解释面上意思,service是业务层,dao是数据访问层.呵呵,这个问题我曾经也有过,记得以前刚学编程的时候,都是在service里直接调用dao,service里面就new一个dao类对象,调用 ...

  9. Android:安卓资源引用符号的含义

    @代表引用资源 @*代表引用系统的非public资源,如: @*android:color/white @[package:]type/name引用自定义资源,如: android:text=&quo ...

  10. 面试常考的数据结构Java实现

    1.线性表 2.线性链表 3.栈 4.队列 5.串 6.数组 7.广义表 8.树和二叉树 的结点),并且,二叉树的子树有左右之分,其次序不能任意颠倒. 二叉树的性质: :在二叉树的第 i 层上至多有2 ...