CRUD与SPA, ASP。NET Web API和Angular.js

介绍 在本文中,我将用AngularJS演示一个简单的CRUD过程,并使用大量的图形表示。一张图片胜过千言万语,因此我相信在一篇文章中配上适当的截屏。这里我将描述你将如何创建CRUD在angularjs。我将展示一些成功的步骤如下: 背景 在visual studio web应用程序中,使用客户端服务器架构。下面是两个进程或两个应用程序,它们将相互通信以交换一些信息。在这两个进程中,一个作为客户端进程,另一个作为服务器。 在传统的web应用程序中,客户机(浏览器)通常向服务器请求页面以启动通信。然后服务器处理请求并将页面的HTML发送给客户机(浏览器)。 在单页面应用程序中,首先通过初始请求将整个页面加载到客户机中,然后后续操作必须通过Ajax请求进行更新,而不需要重新加载整个页面。SPA缩短了响应用户动作的时间,从而使用户体验更加流畅。 开发与传统web应用程序不同的SPA体系结构是非常困难的。然而,最熟悉的技术,如JavaScript框架,如AngularJS, asp . net Web API,以及CSS3的新样式特性,使设计和构建水疗中心变得非常容易。 在本文中,我将向您展示如何使用ASP创建SPA和CRUD。NET Web API, AngularJS。 概述 目标 在这篇文章中,你将学习如何: 使用Twitter-Bootstrap创建一个响应式UI 先决条件 Windows 7或更高版本,至少4GB内存visual Studio Express 2013 for Web 或更大的SQL Server 2012, SQL Server Express,或localdb asp。NET MVC 5 angularjs在60分钟左右的电子书或视频 设置 为了创建此应用程序,请遵循以上先决条件。 练习 本文包括以下练习: 创建一个Web api创建一个SPA接口 练习1:创建Web API 来设置web api应用程序 打开Visual Studio Express 2013 for web并选择文件| New >开始一个新的解决方案。 , 创建新项目 2. 在Visual Studio 2013中通过选择“新建项目”对话框创建一个新的Wep API项目,然后选择ASP。在Visual c# | Web选项卡下的。NET Web应用程序。使sure 。NET Framework 4.5被选中,命名为它,选择一个位置并点击OK。 创建一个新的ASP。NET Web应用项目 3.在,新的ASP。在“网络项目”对话框中,选择“模板”并选择“Web api”选项。Also  Click  OK 继续。 使用MVC模板创建一个新项目,包括Web API组件 4. 在“解决方案资源管理器”中,右键单击项目和构建的解决方案。 构建一个新的解决方案 5. 现在创建数据库“Inventory”和表“Customer”并设置主键Id,下面是脚本: 隐藏,收缩,复制Code

USE [Inventory]
GO

DROP TABLE [dbo].[Customer]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Customer](
    [Id] [int] NOT NULL,
    [Name] [nvarchar](50) NULL,
    [Address] [nvarchar](50) NULL,
    [City] [nvarchar](50) NULL,
    [Country] [nvarchar](50) NULL,
    [DateOfBirth] [datetime] NULL,
    [Age] [int] NULL,
 CONSTRAINT [PK_Customer] PRIMARY KEY CLUSTERED 
 (
    [Id] ASC
 )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = 
 ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
 ) ON [PRIMARY]

 GO

6. 创建数据库和表之后,现在你必须通过这个对话框创建实体框架工作模型对象。 创建实体框架数据模型对象 7. 在实体数据模型向导中,从数据库中选择EF设计器,并按下next按钮 选择实体框架模型内容 8. 在实体数据模型Wizerd选择您的数据连接,但单击新连接…按钮 从“连接属性”对话框中选择“连接字符串” 9. 在“连接属性”窗口对话框中,写入服务器名称、sql身份验证并选择数据库名称,然后完成 从这个窗口中选择连接字符串 10. 在实体数据模型向导中,选择yes,将感兴趣的数据包含在连接字符串中,然后按下next按钮 在连接字符串中选择感知数据。 11. 在实体数据模型向导中,选择表并按finish按钮 创建客户表模型对象 12. 完成上述过程后构建解决方案 13. 在解决方案资源管理器中,右键单击rdlcreportproject的控件文件夹,并选择添加新的控制器项……然后用这种方法创建CustomerController 选择api控制器 选择Api控制器名称 14. 然后将CustomerController.cs 文件添加到rdlcreport项目的controllers&文件夹中,其中包含一个空的customercontrollerler 在RDLCReport.Controllers 名称空间之前添加以下程序集 隐藏,复制Code

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

15. 在CustomerController.cs文件中,添加fol将代码导入customercontroller类。 隐藏,复制Code

InventoryEntities db = new InventoryEntities();

隐藏,复制Code

        //get all customer
        [HttpGet]
        public IEnumerable<Customer> Get()
        {
            return db.Customers.AsEnumerable();
        }

        //get customer by id
        public Customer Get(int id)
        {
            Customer customer = db.Customers.Find(id);
            if (customer == null)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
            }
            return customer;
        }
        

隐藏,复制Code

        //insert customer
        public HttpResponseMessage Post(Customer customer)
        {
            if (ModelState.IsValid)
            {
                db.Customers.Add(customer);
                db.SaveChanges();
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, customer);
                response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = customer.Id }));
                return response;
            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
        }

隐藏,复制Code

        //update customer
        public HttpResponseMessage Put(int id, Customer customer)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
            if (id != customer.Id)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }
            db.Entry(customer).State = EntityState.Modified;
            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
            }
            return Request.CreateResponse(HttpStatusCode.OK);
        }

隐藏,复制Code

        //delete customer by id
        public HttpResponseMessage Delete(int id)
        {
            Customer customer = db.Customers.Find(id);
            if (customer == null)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }
            db.Customers.Remove(customer);
            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
            }
            return Request.CreateResponse(HttpStatusCode.OK, customer);
        }

隐藏,复制Code

        //prevent memory leak
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }

练习2:创建SPA接口 要做的: 1. 从tools&s>Library软件包管理器中打开软件包管理器控制台。输入以下命令来安装angularjs . corenuget包。 隐藏,复制Code

Install-Package AngularJS.Core

2. 在“解决方案资源管理器”中,右键单击rdlcreport项目的脚本文件夹,并选择“添加|新文件夹”。命名文件夹并按Enter键。 3.右键单击刚刚创建的应用文件夹,选择“添加| JavaScript文件”。 创建一个新的JavaScript文件 4. 在“指定项目名称”对话框中,在“项目名称”文本框中键入测验控制按钮,然后单击“确定”。 命名新的JavaScript文件 5. 在customerctr .js 文件中,添加以下代码来声明和初始化AngularJS。 隐藏,收缩,复制Code

    //create angularjs controller
    var app = angular.module('app', []);//set and get the angular module
    app.controller('customerController', ['$scope', '$http', customerController]);

    //angularjs controller method
    function customerController($scope, $http) {

        //declare variable for mainain ajax load and entry or edit mode
        $scope.loading = true;
        $scope.addMode = false;

        //get all customer information
        $http.get('/api/Customer/').success(function (data) {
            $scope.customers = data;
            $scope.loading = false;
        })
        .error(function () {
            $scope.error = "An Error has occured while loading posts!";
            $scope.loading = false;
        });

        //by pressing toggleEdit button ng-click in html, this method will be hit
        $scope.toggleEdit = function () {
            this.customer.editMode = !this.customer.editMode;
        };

        //by pressing toggleAdd button ng-click in html, this method will be hit
        $scope.toggleAdd = function () {
            $scope.addMode = !$scope.addMode;
        };

        //Inser Customer
        $scope.add = function () {
            $scope.loading = true;
            $http.post('/api/Customer/', this.newcustomer).success(function (data) {
                alert("Added Successfully!!");
                $scope.addMode = false;
                $scope.customers.push(data);
                $scope.loading = false;
            }).error(function (data) {
                $scope.error = "An Error has occured while Adding Customer! " + data;
                $scope.loading = false;
            });
        };

        //Edit Customer
        $scope.save = function () {
            alert("Edit");
            $scope.loading = true;
            var frien = this.customer;  
            alert(frien);          
            $http.put('/api/Customer/' + frien.Id, frien).success(function (data) {
                alert("Saved Successfully!!");
                frien.editMode = false;
                $scope.loading = false;
            }).error(function (data) {
                $scope.error = "An Error has occured while Saving customer! " + data;
                $scope.loading = false;
            });
        };

       //Delete Customer
        $scope.deletecustomer = function () {
            $scope.loading = true;
            var Id = this.customer.Id;
            $http.delete('/api/Customer/' + Id).success(function (data) {
                alert("Deleted Successfully!!");
                $.each($scope.customers, function (i) {
                    if ($scope.customers[i].Id === Id) {
                        $scope.customers.splice(i, 1);
                        return false;
                    }
                });
                $scope.loading = false;
            }).error(function (data) {
                $scope.error = "An Error has occured while Saving Customer! " + data;
                $scope.loading = false;
            });
        };

    }

6. 从而,customerCtrl。上面的所有代码,都可以放到这个javascript函数中。 隐藏,复制Code

(function () {
      'use strict';

   /*Write above code here*/

})();

7. _Layout拷贝。路径为views&shared_layout的页面。cshtml,添加以下行 创建角引导指令 8. 在bundleconfig文件中,添加两行,路径为App_Start> BundleConfig.cs 添加java脚本文件 9. ,在Views>Home>索引。cshtml文件添加以下代码 隐藏,收缩,复制Code

<div data-ng-controller="customerController" class="container">
    <div class="row">
        <div class="col-md-12">
            <strong class="error">{{ error }}</strong>
            <p data-ng-hide="addMode"><a data-ng-click="toggleAdd()" href="javascript:;" class="btn btn-primary">Add New</a></p>
            <form name="addCustomer" data-ng-show="addMode" style="width:600px;margin:0px auto;">
                <div class="form-group">
                    <label for="cid" class="col-sm-2 control-label">ID:</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="cid" placeholder="please enter id" data-ng-model="newcustomer.Id" required />
                    </div>
                </div>
                <div class="form-group">
                    <label for="cname" class="col-sm-2 control-label">Name:</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="cname" placeholder="please enter your name" data-ng-model="newcustomer.Name" required />
                    </div>
                </div>
                <div class="form-group">
                    <label for="address" class="col-sm-2 control-label">Address:</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="address" placeholder="please enter your address" data-ng-model="newcustomer.Address" required />
                    </div>
                </div>
                <div class="form-group">
                    <label for="city" class="col-sm-2 control-label">City:</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="city" placeholder="please enter your city" data-ng-model="newcustomer.City" required />
                    </div>
                </div>
                <div class="form-group">
                    <label for="country" class="col-sm-2 control-label">Country:</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="country" placeholder="please enter your country" data-ng-model="newcustomer.Country" required />
                    </div>
                </div>
                <div class="form-group">
                    <label for="age" class="col-sm-2 control-label">Age:</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="age" placeholder="please enter your age" data-ng-model="newcustomer.Age" required />
                    </div>
                </div>
                <br />
                <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                        <input type="submit" value="Add" data-ng-click="add()" data-ng-disabled="!addCustomer.$valid" class="btn btn-primary" />
                        <input type="button" value="Cancel" data-ng-click="toggleAdd()" class="btn btn-primary" />
                    </div>
                </div>
                <br />
            </form>
        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
            <br />
            <br />
        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
            <div class="table-responsive">
                <table class="table table-bordered table-hover" style="width:800px">
                    <tr>
                        <th>#</th>
                        <td>FirstName</td>
                        <th>LastName</th>
                        <th>Address</th>
                        <th>City</th>
                        <th>PostalCode</th>
                        <th>Country</th>
                    </tr>
                    <tr data-ng-repeat="customer in customers">
                        <td><strong data-ng-hide="customer.editMode">{{ customer.Id }}</strong></td>
                        <td>
                            <p data-ng-hide="customer.editMode">{{ customer.Name }}</p>
                            <input data-ng-show="customer.editMode" type="text" data-ng-model="customer.Name" />
                        </td>
                        <td>
                            <p data-ng-hide="customer.editMode">{{ customer.Address }}</p>
                            <input data-ng-show="customer.editMode" type="text" data-ng-model="customer.Address" />
                        </td>
                        <td>
                            <p data-ng-hide="customer.editMode">{{ customer.City }}</p>
                            <input data-ng-show="customer.editMode" type="text" data-ng-model="customer.City" />
                        </td>
                        <td>
                            <p data-ng-hide="customer.editMode">{{ customer.Country }}</p>
                            <input data-ng-show="customer.editMode" type="text" data-ng-model="customer.Country" />
                        </td>
                        <td>
                            <p data-ng-hide="customer.editMode">{{ customer.Age }}</p>
                            <input data-ng-show="customer.editMode" type="text" data-ng-model="customer.Age" />
                        </td>
                        <td>
                            <p data-ng-hide="customer.editMode"><a data-ng-click="toggleEdit(customer)" href="javascript:;">Edit</a> | <a data-ng-click="deletecustomer(customer)" href="javascript:;">Delete</a></p>
                            <p data-ng-show="customer.editMode"><a data-ng-click="save(customer)" href="javascript:;">Save</a> | <a data-ng-click="toggleEdit(customer)" href="javascript:;">Cancel</a></p>
                        </td>
                    </tr>
                </table>
                <hr />
            </div>
        </div>
    </div>
    <div id="mydiv" data-ng-show="loading">
        <img src="Images/ajax-loader.gif" class="ajax-loader" />
    </div>
</div>

10. 跑起来,享受角球的乐趣,输出的结果是: 输出 结论 我认为这篇文章对那些想要先学习AngularJS, WebApi, Twitter-Bootstrap, SPA和SQL-SERVER数据的初学者非常有帮助。我的英语不是很好,如果我有什么错误,请原谅。谢谢你的耐心。 本文转载于:http://www.diyabc.com/frontweb/news15860.html

posted @ 2020-08-12 12:55  Dincat  阅读(289)  评论(0编辑  收藏  举报