Using AngularJS with .NET MVC 5

Posted 大西瓜3721

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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!

技术分享

以上是关于Using AngularJS with .NET MVC 5的主要内容,如果未能解决你的问题,请参考以下文章

Using Kendo with AngularJS

Using Swift with Cocoa and Objective-C下载

http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-an-entity

AspNetCore With Angular SPA Authentication using the Authorization Code Flow

对一个前端使用AngularJS后端使用ASP.NET Web API项目的理解

了解 JDK 7 - try-with-resources