65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 AngularJS 在 ASP.NET MVC-5 中实现 CRUD

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.75/5 (9投票s)

2016 年 1 月 23 日

CPOL

6分钟阅读

viewsIcon

78401

downloadIcon

10059

在本文中,我们将简要概述 AngularJS,然后我们将使用 AngularJS (v1.4.8) 创建一个 ASP.Net MVC-5 CRUD 应用程序。

引言

本文旨在通过 AngularJS 在数据库中执行 CRUD 操作。 

AngularJS 是一个客户端基于 MVC 的 JavaScript 框架。 根据 FAQ,<html> 含有尖括号(<>),因此得名 “Angular”。AngularJS 使用像 ng-app、ng-model 这样的指令,它们都以基础指令“ng”开头,这会让人联想到 “Angular”。

AngularJS 的特点:

  • 开源
  • 由 Google 支持和维护
  • 智能数据绑定。
  • 使用 MVC 设计模式。
  • 智能表单验证
  • 可构建单页应用程序(支持路由)。
  • 松耦合(使用依赖注入-DI)。
  • 易于单元测试 
  • 模块化架构
  • REST 友好 

AngularJS 中的代码-

<body ng-app>
    First Name: <input type="text" ng-model="fname" /> <br />
    Last Name: <input type="text" ng-model="lname" /> <br />
    Result: {{fname +' '+ lname}}
</body>

<script src="Scripts/angular.min.js"></script>

JQuery 中的代码-

<body>
    First Name: <input type="text" id="txtfName" /> <br />
    Last Name: <input type="text" id="txtlName" /> <br />
    Result: <label id="lblName"></label>
</body>

<script src="Scripts/jquery-2.2.0.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $(function () {
            $('#txtfName').keyup(function () {
                $('#lblName').text($('#txtfName').val() + ' ' + $('#txtlName').val());
            });

            $('#txtlName').keyup(function () {
                $('#lblName').text($('#txtfName').val() + ' ' + $('#txtlName').val());
            });
        });
    });
</script>

是不是很酷?接下来我们将了解在哪里可以找到它,以及如何安装它。

下载 AngularJS 库

访问 AngularJS 网站并下载 – https://angularjs.org。 点击“下载”链接以下载最新版本的 AngularJS 库。我们在本应用中使用的是 v1.4.8 版本。

让我们开始吧

让我们打开 Visual Studio 2015 (IDE),点击:[文件 > 新建 > 项目],新窗口出现后点击 ASP.Net Web 应用程序,为项目命名,然后点击右下角的“确定”按钮。

图:1.0

在下一个窗口中选择“空”模板,并勾选 MVC,然后点击“确定”按钮。加载一个示例空项目需要一些时间。

图:1.1

现在我们需要做的第一件事是在此应用程序中注册 AngularJS.Core。我们需要从 NuGet 获取引用。

图:1.2

为此,右键单击项目名称,然后点击“管理 NuGet 程序包”,在下一个窗口中搜索“Angular”并安装 AngularJS.Core 的更新版本。

或者

点击 [ 工具 > NuGet 包管理器 > 程序包管理器控制台 ] 并输入

Install-Package AngularJS.Core

我们还需要在项目中添加 jQuery 库。 我们的安装过程到此结束。 

数据层

public class GenericRepository<T> : IRepository<T> where T : class
{

    CRUD_SampleEntities context = null;
    private DbSet<T> entities = null;

    public GenericRepository(CRUD_SampleEntities context)
    {
        this.context = context;
        entities = context.Set<T>();
    }

    /// <summary>
    /// Get Data From Database
    /// <para>Use it when to retive data through a stored procedure</para>
    /// </summary>
    public IEnumerable<T> ExecuteQuery(string spQuery, object[] parameters)
    {
        using (context = new CRUD_SampleEntities())
        {
            return context.Database.SqlQuery<T>(spQuery, parameters).ToList();
        }
    }

    /// <summary>
    /// Get Single Data From Database
    /// <para>Use it when to retive single data through a stored procedure</para>
    /// </summary>
    public T ExecuteQuerySingle(string spQuery, object[] parameters)
    {
        using (context = new CRUD_SampleEntities())
        {
            return context.Database.SqlQuery<T>(spQuery, parameters).FirstOrDefault();
        }
    }

    /// <summary>
    /// Insert/Update/Delete Data To Database
    /// <para>Use it when to Insert/Update/Delete data through a stored procedure</para>
    /// </summary>
    public int ExecuteCommand(string spQuery, object[] parameters)
    {
        int result = 0;
        try
        {
            using (context = new CRUD_SampleEntities())
            {
                result = context.Database.SqlQuery<int>(spQuery, parameters).FirstOrDefault();
            }
        }
        catch { }
        return result;
    }

    private bool disposed = false;

    protected virtual void Dispose(bool disposing)
    {
        if (!this.disposed)
        {
            if (disposing)
            {
                context.Dispose();
            }
        }
        this.disposed = true;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}

代码解释

如果您对这种设计模式不熟悉,点击此处查看概述以了解更多信息。

接口

interface IRepository<T> : IDisposable where T : class
{
    IEnumerable<T> ExecuteQuery(string spQuery, object[] parameters);
    T ExecuteQuerySingle(string spQuery, object[] parameters);
    int ExecuteCommand(string spQuery, object[] parameters);
}

中间层

public partial class CustomerService
{
    private GenericRepository<Customer> CustRepository;

    public CustomerService()
    {
        this.CustRepository = new GenericRepository<Customer>(new CRUD_SampleEntities());
    }

    public IEnumerable<Customer> GetAll(object[] parameters)
    {
        string spQuery = "[Get_Customer] {0}";
        return CustRepository.ExecuteQuery(spQuery, parameters);
    }

    public Customer GetbyID(object[] parameters)
    {
        string spQuery = "[Get_CustomerbyID] {0}";
        return CustRepository.ExecuteQuerySingle(spQuery, parameters);
    }

    public int Insert(object[] parameters)
    {
        string spQuery = "[Set_Customer] {0}, {1}";
        return CustRepository.ExecuteCommand(spQuery, parameters);
    }

    public int Update(object[] parameters)
    {
        string spQuery = "[Update_Customer] {0}, {1}, {2}";
        return CustRepository.ExecuteCommand(spQuery, parameters);
    }

    public int Delete(object[] parameters)
    {
        string spQuery = "[Delete_Customer] {0}";
        return CustRepository.ExecuteCommand(spQuery, parameters);
    }
}

我们的数据层和服务层已经准备好了。要创建数据库,请下载数据库脚本并使用 MS SQL Server 执行它。让我们创建一个 MVC HomeController 并生成一个空视图。

MVC HomeController

只需将此代码放入您的 HomeController 中,我稍后会解释。

public class HomeController : Controller
{
    private CustomerService objCust;
    public HomeController()
    {
        this.objCust = new CustomerService();
    }

    // GET: Home
    public ActionResult Index()
    {
        return View();
    }

    // GET: All Customer
    [HttpGet]
    public JsonResult GetAllData()
    {
        int Count = 10; IEnumerable<object> customers = null;
        try
        {
            object[] parameters = { Count };
            customers = objCust.GetAll(parameters);
        }
        catch { }
        return Json(customers.ToList(), JsonRequestBehavior.AllowGet);
    }

    // GET: Get Single Customer
    [HttpGet]
    public JsonResult GetbyID(int id)
    {
        object customer = null;
        try
        {
            object[] parameters = { id };
            customer = this.objCust.GetbyID(parameters);
        }
        catch { }
        return Json(customer, JsonRequestBehavior.AllowGet);
    }

    public ActionResult Insert()
    {
        return View();
    }

    // POST: Save New Customer
    [HttpPost]
    public JsonResult Insert(Customer model)
    {
        int result = 0; bool status = false;
        if (ModelState.IsValid)
        {
            try
            {
                object[] parameters = { model.CustName, model.CustEmail };
                result = objCust.Insert(parameters);
                if (result == 1)
                {
                    status = true;
                }
                return Json(new { success = status });
            }
            catch { }
        }
        return Json(new
        {
            success = false,
            errors = ModelState.Keys.SelectMany(i => ModelState[i].Errors).Select(m => m.ErrorMessage).ToArray()
        });
    }

    public ActionResult Update()
    {
        return View();
    }

    // POST: Update Existing Customer
    [HttpPost]
    public JsonResult Update(Customer model)
    {
        int result = 0; bool status = false;
        if (ModelState.IsValid)
        {
            try
            {
                object[] parameters = { model.Id, model.CustName, model.CustEmail };
                result = objCust.Update(parameters);
                if (result == 1)
                {
                    status = true;
                }
                return Json(new { success = status });
            }
            catch { }
        }
        return Json(new
        {
            success = false,
            errors = ModelState.Keys.SelectMany(i => ModelState[i].Errors).Select(m => m.ErrorMessage).ToArray()
        });
    }

    // DELETE: Delete Customer
    [HttpDelete]
    public JsonResult Delete(int id)
    {
        int result = 0; bool status = false;
        try
        {
            object[] parameters = { id };
            result = objCust.Delete(parameters);
            if (result == 1)
            {
                status = true;
            }
        }
        catch { }
        return Json(new 
        { 
            success = status        
        });
    }

    protected override void Dispose(bool disposing)
    {
        base.Dispose(disposing);
    }
}

代码解释

让我们逐部分解释代码。

获取所有记录: 以下代码示例用于通过我们的中间层/服务层从数据库获取所有记录。 这里我们返回 JSON 数据。 JSON 数据的格式易于阅读,遵循属性-值对。最初我们获取十(10)条记录,这是为视图页面的分页做准备。

// GET: All Customer
[HttpGet]
public JsonResult GetAllData()
{
    int Count = 10; IEnumerable<object> customers = null;
    try
    {
        object[] parameters = { Count };
        customers = objCust.GetAll(parameters);
    }
    catch { }
    return Json(customers.ToList(), JsonRequestBehavior.AllowGet);
}

注意,当我们返回数据列表时,我们设置了 "JsonRequestBehavior.AllowGet"。 如果我们漏掉了这个,就会出现以下错误消息

This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. 
To allow GET requests, set JsonRequestBehavior to AllowGet.

为什么要使用它?如果你仔细阅读那条消息, 答案就在里面。这是出于安全原因。

获取单条记录详情: 以下代码示例用于从数据库检索单条选定记录的详情,同样返回 JSON 数据格式。

// GET: Get Single Customer
[HttpGet]
public JsonResult GetbyID(int id)
{
    object customer = null;
    try
    {
        object[] parameters = { id };
        customer = this.objCust.GetbyID(parameters);
    }
    catch { }
    return Json(customer, JsonRequestBehavior.AllowGet);
}

插入记录: 以下代码示例将向数据库插入/保存记录详情,它返回一个布尔数据类型的 JSON 结果。如果为 true,则表示数据已成功插入数据库。

// POST: Save New Customer
[HttpPost]
public JsonResult Insert(Customer model)
{
    int result = 0; bool status = false;
    if (ModelState.IsValid)
    {
        try
        {
            object[] parameters = { model.CustName, model.CustEmail };
            result = objCust.Insert(parameters);
            if (result == 1)
            {
                status = true;
            }
            return Json(new { success = status });
        }
        catch { }
    }
    return Json(new
    {
        success = false,
        errors = ModelState.Keys.SelectMany(i => ModelState[i].Errors).Select(m => m.ErrorMessage).ToArray()
    });
}

更新记录: 以下代码示例将更新数据库中选定的现有记录详情,它也返回一个布尔数据类型的 JSON 结果。和之前一样,如果为 true,则表示数据已成功更新到数据库。

// POST: Update Existing Customer
[HttpPost]
public JsonResult Update(Customer model)
{
    int result = 0; bool status = false;
    if (ModelState.IsValid)
    {
        try
        {
            object[] parameters = { model.Id, model.CustName, model.CustEmail };
            result = objCust.Update(parameters);
            if (result == 1)
            {
                status = true;
            }
            return Json(new { success = status });
        }
        catch { }
    }
    return Json(new
    {
        success = false,
        errors = ModelState.Keys.SelectMany(i => ModelState[i].Errors).Select(m => m.ErrorMessage).ToArray()
    });
}

删除记录: 以下代码示例将从数据库删除选定的现有记录详情,它也返回一个布尔数据类型的 JSON 结果。如果为 true,则表示数据已成功从数据库删除。

// DELETE: Delete Customer
[HttpDelete]
public JsonResult Delete(int id)
{
    int result = 0; bool status = false;
    try
    {
        object[] parameters = { id };
        result = objCust.Delete(parameters);
        if (result == 1)
        {
            status = true;
        }
    }
    catch { }
    return Json(new 
    { 
        success = status
    });
}

我们的 MVC 控制器已经完成了在数据库中执行 CRUD 操作的功能。现在让我们进入下一部分,即 AngularJS 部分。

AngularJS(JavaScript) 控制器

angular.module('myFormApp', [])
.controller('CustomerController', function ($scope, $http, $location, $window) {
    $scope.custModel = {};
    $scope.message = '';
    $scope.result = "color-default";
    $scope.isViewLoading = false;
    $scope.ListCustomer = null;
    getallData();

    //******=========Get All Customer=========******
    function getallData() {
        //debugger;
        $http.get('/Home/GetAllData')
         .success(function (data, status, headers, config) {
             $scope.ListCustomer = data;
         })
         .error(function (data, status, headers, config) {
             $scope.message = 'Unexpected Error while loading data!!';
             $scope.result = "color-red";
             console.log($scope.message);
         });
    };

    //******=========Get Single Customer=========******
    $scope.getCustomer = function (custModel) {
        $http.get('/Home/GetbyID/' + custModel.Id)
        .success(function (data, status, headers, config) {
            //debugger;
            $scope.custModel = data;
            getallData();
            console.log(data);
        })
       .error(function (data, status, headers, config) {
           $scope.message = 'Unexpected Error while loading data!!';
           $scope.result = "color-red";
           console.log($scope.message);
       });
    };

    //******=========Save Customer=========******
    $scope.saveCustomer = function () {
        $scope.isViewLoading = true;

        $http({
            method: 'POST',
            url: '/Home/Insert',
            data: $scope.custModel
        }).success(function (data, status, headers, config) {
            if (data.success === true) {
                $scope.message = 'Form data Saved!';
                $scope.result = "color-green";
                getallData();
                $scope.custModel = {};
                console.log(data);
            }
            else {
                $scope.message = 'Form data not Saved!';
                $scope.result = "color-red";
            }
        }).error(function (data, status, headers, config) {
            $scope.message = 'Unexpected Error while saving data!!' + data.errors;
            $scope.result = "color-red";
            console.log($scope.message);
        });
        getallData();
        $scope.isViewLoading = false;
    };

    //******=========Edit Customer=========******
    $scope.updateCustomer = function () {
        //debugger;
        $scope.isViewLoading = true;
        $http({
            method: 'POST',
            url: '/Home/Update',
            data: $scope.custModel
        }).success(function (data, status, headers, config) {
            if (data.success === true) {
                $scope.custModel = null;
                $scope.message = 'Form data Updated!';
                $scope.result = "color-green";
                getallData();
                console.log(data);
            }
            else {
                $scope.message = 'Form data not Updated!';
                $scope.result = "color-red";
            }
        }).error(function (data, status, headers, config) {
            $scope.message = 'Unexpected Error while updating data!!' + data.errors;
            $scope.result = "color-red";
            console.log($scope.message);
        });
        $scope.isViewLoading = false;
    };

    //******=========Delete Customer=========******
    $scope.deleteCustomer = function (custModel) {
        //debugger;
        var IsConf = confirm('You are about to delete ' + custModel.CustName + '. Are you sure?');
        if (IsConf) {
            $http.delete('/Home/Delete/' + custModel.Id)
           .success(function (data, status, headers, config) {
               if (data.success === true) {
                   $scope.message = custModel.CustName + ' deleted from record!!';
                   $scope.result = "color-green";
                   getallData();
                   console.log(data);
               }
               else {
                   $scope.message = 'Error on deleting Record!';
                   $scope.result = "color-red";
               }
           })
           .error(function (data, status, headers, config) {
               $scope.message = 'Unexpected Error while deleting data!!';
               $scope.result = "color-red";
               console.log($scope.message);
           });
        }
    };
})
.config(function ($locationProvider) {
    $locationProvider.html5Mode(true);
});

代码解释

$http 是 AngularJS 的核心服务,可以与远程 HTTP 服务器进行通信。 用于通信的 HTTP 方法有

  • $http.get: 获取数据
  • $http.post: 提交新数据
  • $http.put: 更新现有数据
  • $http.delete: 删除现有数据

在此处了解更多关于 $http 服务的信息

获取所有记录:我们使用 $http.get 方法从数据库检索所有记录。

//******=========Get All Customer=========******
function getallData() {
    //debugger;
    $http.get('/Home/GetAllData')
        .success(function (data, status, headers, config) {
            $scope.ListCustomer = data;
        })
        .error(function (data, status, headers, config) {
            $scope.message = 'Unexpected Error while loading data!!';
            $scope.result = "color-red";
            console.log($scope.message);
        });
};

获取单条记录: 在这里,我们从数据库中检索现有的客户记录。当点击编辑按钮时,会调用 $scope.getCustomer 方法。

//******=========Get Single Customer=========******
$scope.getCustomer = function (custModel) {
    $http.get('/Home/GetbyID/' + custModel.Id)
    .success(function (data, status, headers, config) {
        //debugger;
        $scope.custModel = data;
        getallData();
        console.log(data);
    })
    .error(function (data, status, headers, config) {
        $scope.message = 'Unexpected Error while loading data!!';
        $scope.result = "color-red";
        console.log($scope.message);
    });
};

我们使用 $http.get 方法,通过将客户 ID 传递给 MVC 控制器的更新方法,从数据库中检索选定的客户记录。作为回报,我们获取查询数据,然后 AngularJS 的 $scope.custModel 通过 ng-model 将数据绑定到输入模型,我们知道 AngularJS 支持双向数据绑定。

在此处了解更多关于双向数据绑定的信息

保存记录:在这里我们保存客户记录。当我们在用户界面上点击提交按钮,提交带有客户信息的表单时,会调用 $scope.saveCustomer 方法。我们使用 $http.post 将客户对象传递给我们的 MVC 控制器。

//******=========Save Customer=========******
$scope.saveCustomer = function () {
    $scope.isViewLoading = true;

    $http({
        method: 'POST',
        url: '/Home/Insert',
        data: $scope.custModel
    }).success(function (data, status, headers, config) {
        if (data.success === true) {
            $scope.message = 'Form data Saved!';
            $scope.result = "color-green";
            getallData();
            $scope.custModel = {};
            console.log(data);
        }
        else {
            $scope.message = 'Form data not Saved!';
            $scope.result = "color-red";
        }
    }).error(function (data, status, headers, config) {
        $scope.message = 'Unexpected Error while saving data!!' + data.errors;
        $scope.result = "color-red";
        console.log($scope.message);
    });
    getallData();
    $scope.isViewLoading = false;
};

控制器完成剩余工作,并返回一个表示保存成功与否的状态。成功插入后,我们重新加载了数据表(再次调用 getallData() 方法)。

编辑记录: 在这里我们更新数据库中现有的客户记录。当点击更新按钮时,会调用 $scope.updateCustomer 方法。与保存记录类似,这里也发生了同样的事情。保存和更新的主要区别在于客户 ID。这次我们传递了带有客户对象的客户 ID,该 ID 是从一个隐藏输入字段中获取的。

<input type="hidden" ng-model="custModel.Id" name="cid" />

我们使用 $http.post 将客户对象传递给我们的 MVC 控制器。

//******=========Edit Customer=========******
$scope.updateCustomer = function () {
    //debugger;
    $scope.isViewLoading = true;
    $http({
        method: 'POST',
        url: '/Home/Update',
        data: $scope.custModel
    }).success(function (data, status, headers, config) {
        if (data.success === true) {
            $scope.custModel = null;
            $scope.message = 'Form data Updated!';
            $scope.result = "color-green";
            getallData();
            console.log(data);
        }
        else {
            $scope.message = 'Form data not Updated!';
            $scope.result = "color-red";
        }
    }).error(function (data, status, headers, config) {
        $scope.errors = [];
        $scope.message = 'Unexpected Error while updating data!!' + data.errors;
        $scope.result = "color-red";
        console.log($scope.message);
    });
    $scope.isViewLoading = false;
};

控制器完成剩余工作,并返回一个表示更新成功与否的状态。成功更新后,我们重新加载了数据表(再次调用 getallData() 方法)。

删除记录: 在这里,我们从数据库中删除现有的客户记录。当点击删除按钮时,会调用 $scope.deleteCustomer 方法。

//******=========Delete Customer=========******
$scope.deleteCustomer = function (custModel) {
    //debugger;
    var IsConf = confirm('You are about to delete ' + custModel.CustName + '. Are you sure?');
    if (IsConf) {
        $http.delete('/Home/Delete/' + custModel.Id)
        .success(function (data, status, headers, config) {
            if (data.success === true) {
                $scope.message = custModel.CustName + ' deleted from record!!';
                $scope.result = "color-red";
                getallData();
                console.log(data);
            }
            else {
                $scope.message = 'Error on deleting Record!';
                $scope.result = "color-red";
            }
        })
        .error(function (data, status, headers, config) {
            $scope.message = 'Unexpected Error while deleting data!!';
            $scope.result = "color-red";
            console.log($scope.message);
        });
    }
};

让我们进入 UI/视图部分。这是我们以图形方式执行 CRUD 操作的 Index 视图。

Html 视图

@{
    ViewBag.Title = "Index";
}

<h2>Create Customer</h2>

<div id="content" ng-controller="CustomerController">
    <span ng-show="isViewLoading" class="viewLoading">
        <img src="~/Content/images/ng-loader.gif" /> loading...
    </span>
    <div ng-class="result">{{message}}</div>
    <hr />
    <form name="frmCustomer" novalidate>
        <div>
            <input type="hidden" ng-model="custModel.Id" name="cid" />
        </div>
        <div>
            <label for="email">Customer Name</label>
            <input type="text" ng-model="custModel.CustName" name="cname" placeholder="" required ng-minlength="4" ng-maxlength="14" />
            <span class="error" ng-show="(frmCustomer.$dirty||submitted) && frmCustomer.cname.$error.required">Customer name is Required</span>
            <span class="error" ng-show="frmCustomer.$dirty && frmCustomer.cname.$error.minlength">Minimum length required is 5</span>
            <span class="error" ng-show="frmCustomer.$dirty && frmCustomer.cname.$error.maxlength">Minimum length required is 15</span>
        </div>
        <div>
            <label for="email">E-mail address</label>
            <input type="email" ng-model="custModel.CustEmail" name="email" placeholder="" required />
            <span class="error" ng-show="(frmCustomer.$dirty ||submitted) && frmCustomer.email.$error.required">EmailId is Required!</span>
            <span class="error" ng-show="(frmCustomer.$dirty ||submitted) && frmCustomer.$error.email">Invalid EmailId!</span>
        </div>
        <div class="btn">
            <input type="submit" value="Save" ng-click="saveCustomer()" ng-disabled="frmCustomer.$invalid">
            <input type="submit" value="Update" ng-click="updateCustomer()" ng-disabled="frmCustomer.$invalid">
        </div>
    </form>
    <hr />

    <h2>All Customers</h2>
    <table class="table table-striped">
        <tr ng-repeat="custModel in ListCustomer">
            <td>{{custModel.Id}}</td>
            <td>{{custModel.CustName}}</td>
            <td>{{custModel.CustEmail}}</td>
            <td>
                <a href="#" ng-click="getCustomer(custModel)" title="Edit Record">
                    <img src="~/Content/images/edit.png" />
                </a><a href="#" ng-click="deleteCustomer(custModel)" title="Delete Record">
                    <img src="~/Content/images/erase.png" />
                </a>
            </td>
        </tr>
    </table>
</div>

@section JavaScript{
    <script src="~/Scripts/angular.js"></script>
    <script src="~/ScriptsNg/CustomerController.js"></script>
}

代码解释

以下代码示例是一个带有重复表格行(<tr>)的表格。在这里,ng-repeat 对 ListCustomer 中的每条记录,都使用其模板显示一条记录(custModel),或者简单地说,它就像表格行的重复器。

在此处了解更多关于 ng-repeat 的信息

<table class="table table-striped">
    <tr ng-repeat="custModel in ListCustomer">
        <td>{{custModel.Id}}</td>
        <td>{{custModel.CustName}}</td>
        <td>{{custModel.CustEmail}}</td>
        <td>
            <a href="#" ng-click="getCustomer(custModel)" title="Edit Record">
                <img src="~/Content/images/edit.png" />
            </a><a href="#" ng-click="deleteCustomer(custModel)" title="Delete Record">
                <img src="~/Content/images/erase.png" />
            </a>
        </td>
    </tr>
</table>

我们差不多完成了。让我们用 CSS 来美化我们的用户界面,下面是我们用来美化 UI 的 CSS。

表单样式

#content label {
    width: 150px;
}

.btn {
    margin-left: 140px;
}

#content input[type=submit] {
    width: 85px;
    padding: 5px 15px;
    background: #ff6a00;
    border: 0 none;
    cursor: pointer;
    color: #fff;
}

.error {
    color: red;
}

.color-default {
    color: #000;
}

.color-red {
    color: red;
}

.color-green {
    color: green;
}

#content input.ng-dirty.ng-invalid {
    border: 1px solid red;
    background-color: rgb(255, 244, 244);
}

[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  display: none !important;
}

隐藏 HTML 闪烁 (ng-cloak)

在加载页面时,您可能会注意到 Angular 的 HTML 模板是可见的/会闪烁。这发生在浏览器编译 Angular HTML 模板的过程中,通常在页面加载时会闪烁。这可以使用“ng-cloak/data-ng-cloak”指令来隐藏。

在此处了解更多关于 ng-cloak 的信息

我们还需要在应用程序的起点添加 CSS 类。

<body ng-app="myFormApp" class="ng-cloak">

下面是使用 ng-cloak 的 CSS 类。

[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  display: none !important;
}

让我们在 HomeController 的 Updater() 方法上设置一个断点并运行它,提交表单后,它将命中该断点。

图:1.3

在调试模式下,我们可以看到模型已经填充了表单数据。 我们也可以通过在脚本中放置 debugger 来使用浏览器进行调试。

$scope.updateCustomer = function () {
  debugger;
};

图:1.4

在浏览器的调试模式下,我们可以看到 $scope.custModel 已经填充了表单数据,这些数据将用于更新数据库中选定的记录。

最终输出

[转到浏览器:检查 > 控制台]

[浏览器:检查 > 网络]

希望这篇文章能帮助你走上学习 AngularJS 的道路。圆满结束 :)

© . All rights reserved.