MVC5使用Angular.Js實現Crud

風靈使發表於2018-09-15

CelularModel.cs

using System.ComponentModel.DataAnnotations;

namespace Angular.App.Data.EntityConfig
{
    public class CelularModel
    {
        public int Id { get; set; }
        [Required(ErrorMessage = "填寫品牌領域")]
        public string Marca { get; set; }
        public string Modelo { get; set; }
        public string Cor { get; set; }
        public string TipoChip { get; set; }
        public string MemoriaInterna { get; set; }

    }
}

CelularRepository.cs

using Angular.App.Data.EntityConfig;
using Dapper;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;

namespace Angular.App.Data.Repository
{
    public class CelularRepository
    {
        private readonly DataContext _context = new DataContext();

        //獲取晶片型別
        public CelularModel ObterPorTipoChip(string tipoChip)
        {
            var sql = @"select * from celulares c" + "Where c.tipochip = @tipoChip";

            using (var cn = _context.Database.Connection)
            {
                cn.Open();
                var cliente = cn.Query<CelularModel>(sql);
                return cliente.FirstOrDefault();
            }
        }

        //按品牌獲取
        public CelularModel ObterPorMarca(string marca)
        {
            var sql = @"select * from celulares c" + "Where c.marca = @marca";

            using (var cn = _context.Database.Connection)
            {
                cn.Open();
                var cliente = cn.Query<CelularModel>(sql);
                return cliente.FirstOrDefault();
            }
        }

        //由Id
        public CelularModel ObterPorId(int id)
        {
            var sql = @"select * from celulares c " + "Where c.id = @id";

            using (var cn = _context.Database.Connection)
            {
                cn.Open();
                var cliente = cn.Query<CelularModel>(sql, new { id = id });
                return cliente.FirstOrDefault();
            }
        }

        public IQueryable<CelularModel> ObterTodos()
        {
            return _context.Celular;
        }

        //更新
        public void Atualizar(CelularModel celular)
        {
            _context.Entry(celular).State = EntityState.Modified;
            _context.SaveChanges();
        }

        //新增
        public void Incluir(CelularModel celular)
        {
            _context.Celular.Add(celular);
            _context.SaveChanges();
        }

        //刪除
        public void Excluir(int id)
        {
            _context.Celular.Remove(_context.Celular.Find(id));
            _context.SaveChanges();
        }

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

ClienteService.cs

using Angular.App.Data.EntityConfig;
using Angular.App.Data.Repository;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Angular.App.Application
{
    public class ClienteService
    {
        private CelularRepository _repository = new CelularRepository();

        public CelularModel ObterPorTipoChip(string tipoChip)
        {
            return _repository.ObterPorTipoChip(tipoChip);
        }

        public CelularModel ObterPorId(int id)
        {
            return _repository.ObterPorId(id);
        }

        public IQueryable<CelularModel> ObterTodos()
        {
            return _repository.ObterTodos();
        }

        public void Atualizar(CelularModel celular)
        {
            _repository.Atualizar(celular);
        }

        public void Incluir(CelularModel celular)
        {
            _repository.Incluir(celular);
        }

        public void Excluir(int id)
        {
            _repository.Excluir(id);
        }

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

    }
}

DataContext.cs

using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using Angular.App.Data.EntityConfig;

namespace Angular.App.Data
{
    public class DataContext : DbContext
    {
        public DataContext()
            : base("DefaultConnection")
        {

        }

        public DbSet<CelularModel> Celular { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
            modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();

            modelBuilder.Configurations.Add(new CelularConfiguration());
        }
    }
}

CelularConfiguration.cs

using System.Data.Entity.ModelConfiguration;

namespace Angular.App.Data.EntityConfig
{
    public class CelularConfiguration: EntityTypeConfiguration<CelularModel>
    {
        public CelularConfiguration()
        {
            HasKey(c => c.Id);
            Property(c => c.Marca).IsRequired().HasMaxLength(50);
            Property(c => c.Modelo).IsRequired().HasMaxLength(50);
            Property(c => c.Cor).IsRequired().HasMaxLength(30);
            Property(c => c.TipoChip).IsRequired().HasMaxLength(30);
            Property(c => c.MemoriaInterna).IsRequired().HasMaxLength(3);

            ToTable("Celulares");
        }
    }
}

CelularController.cs

using Angular.App.Application;
using Angular.App.Data.EntityConfig;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace Angular.App.UI.Controllers
{
    [RoutePrefix("api/v1/public")]
    public class CelularController : ApiController
    {
        private ClienteService _db = new ClienteService();

        [HttpGet]
        [Route("celulares")]
        //獲取所有手機
        public IQueryable<CelularModel> ObterTodosCelulares()
        {
            return _db.ObterTodos();
        }

        [HttpGet]
        [Route("celular/{id:int}")]

        //通過ID獲取手機
        public HttpResponseMessage ObterCelularPorId(int id)
        {
            if (id <= 0)
                return Request.CreateResponse(HttpStatusCode.BadRequest);

            return Request.CreateResponse(HttpStatusCode.OK, _db.ObterPorId(id));
        }

        [HttpPut]
        [Route("putCelular")]
        //更新手機
        public HttpResponseMessage AtualizarCelular(CelularModel celular)
        {
            if (celular == null)
                return Request.CreateResponse(HttpStatusCode.BadRequest);

            _db.Atualizar(celular);

            return Request.CreateResponse(HttpStatusCode.OK);
        }

        [HttpPost]
        [Route("postCelular")]
        //新增手機
        public HttpResponseMessage AdicionarCelular(CelularModel celular)
        {
            if (celular == null)
                return Request.CreateResponse(HttpStatusCode.BadRequest);

            _db.Incluir(celular);

            return Request.CreateResponse(HttpStatusCode.OK);
        }

        [HttpDelete]
        [Route("deleteCelular/{id:int}")]

        //刪除手機
        public HttpResponseMessage RemoverCelular(int id)
        {
            if (id <= 0)
                return Request.CreateResponse(HttpStatusCode.BadRequest);

            _db.Excluir(id);
            return Request.CreateResponse(HttpStatusCode.OK);
        }
    }
}

HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Angular.App.UI.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

    }
}

Index.cshtml

@{
    ViewBag.Title = "Home Page";
}

<div ng-controller="crudController">
    <div class="divList">
        <p><b><i>所有的手機</i></b></p>
        <table class="table table-hover table-responsive">
            <tr>
                <td><b>Id</b></td>
                <td><b>品牌</b></td>
                <td><b>型號</b></td>
                <td><b>顏色</b></td>
                <td><b>晶片</b></td>
                <td><b>記憶體</b></td>
            </tr>
            <tbody>
                <tr ng-repeat="celular in celulares">
                    <td>{{celular.Id}}</td>
                    <td>{{celular.Marca}}</td>
                    <td>{{celular.Modelo}}</td>
                    <td>{{celular.Cor}}</td>
                    <td>{{celular.TipoChip}}</td>
                    <td>{{celular.MemoriaInterna}}</td>

                    <td>
                        <span ng-click="obterCelularPorId(celular)" class="btn btn-primary">修改</span>
                        <span ng-click="removerCelular(celular)" class="btn btn-danger">清除</span>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
    <span ng-click="incluirCelularDiv()" class="btn btn-default">新增手機</span>
    <div ng-show="divCelular">
        <p class="divHead"></p>
        <table class="table">
            <tr>
                <td><b><i>{{Acao}}手機</i></b></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
            </tr>
            <tr>
                <td><b>Id</b></td>
                <td>
                    <input type="text" disabled="disabled" ng-model="celularId" class="form-control" />
                </td>
                <td><b>品牌</b></td>
                <td>
                    <input type="text" ng-model="Marca" class="form-control" />
                </td>
            </tr>
            <tr>
                <td><b>型號</b></td>
                <td>
                    <input type="text" ng-model="Modelo" class="form-control" />
                </td>
                <td><b>顏色</b></td>
                <td>
                    <input type="text" ng-model="Cor" class="form-control" />
                </td>
            </tr>
            <tr>
                <td><b>記憶體</b></td>
                <td>
                    <input type="text" ng-model="MemoriaInterna" class="form-control" />
                </td>
                <td><b>晶片型別</b></td>
                <td>
                    <input type="text" ng-model="TipoChip" class="form-control" />
                </td>

            </tr>
            <tr>

                <td></td>
                <td>
                    <input type="button" class="btn btn-default" value="儲存" ng-click="AdicionarAtualizarCelular()" />
                    <input type="button" class="btn btn-danger" value="取消" ng-click="Cancelar()" />
                </td>
            </tr>
        </table>
    </div>

</div>

<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/toastr.js"></script>
<script type="text/javascript">

    var app = angular.module("crudApp", []);
    app.service("crudService", function ($http) {

        this.ObterTodosCelulares = function () {
            return $http.get('/api/v1/public/celulares');
        }

        this.ObterCelularPorId = function (id) {
            return $http.get('/api/v1/public/celular/' + id);
        }

        this.AtualizarCelular = function (celular) {
            var response = $http({
                method: 'put',
                url: '/api/v1/public/putCelular',
                data: JSON.stringify(celular),
                dataType: "json"
            });
            return response;
        }

        this.AdicionarCelular = function (celular) {
            var response = $http({
                method: 'post',
                url: '/api/v1/public/postCelular',
                data: JSON.stringify(celular),
                dataType: "json"
            });
            return response;
        }

        this.RemoverCelular = function (id) {
            return $http.delete('/api/v1/public/deleteCelular/' + id);
        }
    });


    app.controller("crudController", function ($scope, crudService) {
        $scope.divCelular = false;
        obterTodosCelulares();

        function obterTodosCelulares() {
            var celularesData = crudService.ObterTodosCelulares();
            celularesData.then(function (celular) {
                $scope.celulares = celular.data;
            }, function () {
                toastr["error"]("提取手機時出錯", "手機商店")
            })
        }

        $scope.removerCelular = function (celular) {
            var celularData = crudService.RemoverCelular(celular.Id);
            celularData.then(function (data) {
                if (data.status == 200) {
                    toastr["success"]("手機刪除成功!", "Celulares Store")
                }
                obterTodosCelulares();
            }, function () {
                toastr["error"]("刪除時出錯", "手機商店")
            })
        }

        $scope.obterCelularPorId = function (celular) {
            var celularData = crudService.ObterCelularPorId(celular.Id);

            celularData.then(function (_celular) {
                $scope.celular = _celular.data;
                $scope.celularId = celular.Id;
                $scope.Marca = celular.Marca;
                $scope.Modelo = celular.Modelo;
                $scope.Cor = celular.Cor;
                $scope.TipoChip = celular.TipoChip;
                $scope.MemoriaInterna = celular.MemoriaInterna;
                $scope.Action = "AtualizarCelular";
                $scope.divCelular = true;
            }, function () {
                toastr["error"]("載入您的手機時出錯", "Celulares Store")
            });
        }

        $scope.AdicionarAtualizarCelular = function () {

            var celular = {
                Marca: $scope.Marca,
                Modelo: $scope.Modelo,
                Cor: $scope.Cor,
                TipoChip: $scope.TipoChip,
                MemoriaInterna: $scope.MemoriaInterna
            };
            var valorAcao = $scope.Action;

            if (valorAcao == "AtualizarCelular") {

                celular.Id = $scope.celularId;
                var celularData = crudService.AtualizarCelular(celular);
                celularData.then(function (data) {
                    obterTodosCelulares();
                    $scope.divCelular = false;
                    if (data.status == 200) {
                        toastr["success"]("手機改變成功!", "Celulares Store");
                    }
                }, function () {
                    toastr["error"]("錯誤更新!", "Celulares Store");
                });
            } else {

                var celularData = crudService.AdicionarCelular(celular);
                celularData.then(function (data) {
                    obterTodosCelulares();

                    if (data.status == 200) {
                        toastr["success"]("手機成功註冊!", "Celulares Store");
                    }
                    $scope.divCelular = false;
                }, function () {
                    toastr["error"]("錯誤包括!", "Celulares Store");
                });
            }
        }

        $scope.incluirCelularDiv = function () {
            limparCampos();
            $scope.Action = "AdicionarCelular";
            $scope.divCelular = true;
        }

        $scope.Cancelar = function () {
            $scope.divCelular = false;
        };

        function limparCampos() {
            $scope.celularId = "";
            $scope.Marca = "";
            $scope.Modelo = "";
            $scope.Cor = "";
            $scope.TipoChip = "";
            $scope.MemoriaInterna = "";
        }
    });

</script>

_Layout.cshtml

<!DOCTYPE html>
<html ng-app="crudApp">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Styles.Render("~/Content/toastr")
    @Scripts.Render("~/bundles/modernizr")


    @Scripts.Render("~/bundles/jquery")
    @*@Scripts.Render("~/bundles/angular")
        @Scripts.Render("~/bundles/customJs")
        @Scripts.Render("~/bundles/toastrjs")*@
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                </ul>
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

</body>
</html>

執行如圖:

這裡寫圖片描述

相關文章