• ABP增删改查代码片段


    @using System.Web.Optimization
    @using MultiPageSimpleTask.Entitys.Dtos;
    @model IList<ProductDto>
    @{
        Layout = null;
        ProductDto productDto = ViewBag.SingleProduct as ProductDto;
    }
    <!doctype html>
    <html ng-app>
    <head>
        <title>Hello World</title>
        @Scripts.Render("~/Bundles/vendor/js/bottom")
        <script type="text/javascript">
            $(function () {
                //批量新增 工作单元
                $("#AddBtnbatch").click(function () {
                    $.ajax({
                        type: "post",
                        url: '@Url.Action("AddProductbatch", "Home")',
                        success: function (data) {
                            //console.log(data);
                            var result = data;
                            if (result.Status) {
                                alert("新增成功");
                                //top.window.location = '/Home/Index';
                            } else {
                                alert("新增失败
    " + result.Message);
                            }
                        }
                    });
                });
                $(".linkDel").click(function () {
                    var pid = $(this).attr("data-pid");
                    $.ajax({
                        type: "POST",
                        url: '@Url.Action("Delete", "Home")',
                        data: { "id": pid },
                        success: function (data) {
                            //console.log(data);
                            var result = data;
                            if (result.Status) {
                                alert("删除成功");
                                //top.window.location = '/Home/Index';
                            } else {
                                alert("删除失败");
                            }
                        }
                    });
                });
            });
        </script>
    </head>
    <body>
        <a href="@Url.Action("Add","Home")" target="_blank">新增商品</a>
        <br /><br />
        <input type="button" name="AddBtnbatch" id="AddBtnbatch" value="新增多条数据(工作单元)" />
        <br /><br />
    
        单个商品信息 ID @productDto.Id 名称 @productDto.ProductName
        <br /><br />
        数据总数 @ViewBag.TotalCount 总共 @ViewBag.PageCount 页<br />
        <ul>
            @foreach (var Product in Model)
            {
                <li>
                    <span>
                        @(string.Format("{0}-{1}", Product.Id.ToString(), Product.ProductName))
                        [<a href="@Url.Action("Update", "Home", new { id = Product.Id })" target="_blank">修改商品</a>]
                        [<a href="javascript:void(0);" class="linkDel" data-pid="@Product.Id">删除商品</a>]
                    </span>
                </li>
            }
        </ul>
    </body>
    </html>
    
    using System;
    using System.Text;
    using System.Collections.Generic;
    using System.Web.Mvc;
    using Abp.AutoMapper;
    using Abp.Domain.Uow;
    using AutoMapper;
    using MultiPageSimpleTask.Entitys;
    using MultiPageSimpleTask.Entitys.Dtos;
    
    
    namespace MultiPageSimpleTask.Web.Controllers
    {
        public class HomeController : MultiPageSimpleTaskControllerBase
        {
            private readonly StatusMsg _result = new StatusMsg();
            private readonly ICategoryRepository _categoryAppService;
    
            private readonly IProductRepository _productAppService;
            private readonly IUnitOfWorkManager _unitOfWorkManager;
    
            public HomeController(ICategoryRepository categoryAppService,
                                  IProductRepository productAppService, IUnitOfWorkManager unitOfWorkManager)
            {
                _categoryAppService = categoryAppService;
                _productAppService = productAppService;
                _unitOfWorkManager = unitOfWorkManager;
            }
    
            #region 首页
            public ActionResult Index()
            {
                string strSql = "select productID as id,* from product"; //一定添加别名ID列,否则报错
                string orderfied = "order by ProductId ";
                int totalCount = 0;
                int pageCount = 0;
                //获取分页商品列表
                var lists = _productAppService.GetQueryPager(strSql, 2, 10, orderfied, ref totalCount, ref pageCount);
                //TODO:Used AutoMapper to automatically convert List<Product> to List<ProductDto>.
                List<ProductDto> produscts = Mapper.Map<List<ProductDto>>(lists);
                //获取某一个商品
                var product = _productAppService.Get(2);
                ViewBag.SingleProduct = Mapper.Map<ProductDto>(product);
                ViewBag.TotalCount = totalCount;
                ViewBag.PageCount = pageCount;
                return View(produscts);
            }
            #endregion
    
            #region 新增商品
            [HttpGet]
            public ActionResult Add()
            {
                Entitys.Product product = new Entitys.Product();
                return View(product);
            }
    
            [HttpPost]
            public ActionResult Add(Entitys.Product model)
            {
                _result.Status = false;
                //TODO:Convert to DTOs
                if (!ModelState.IsValid)
                {
                    _result.Message = ExpendErrors(this);
                }
                else
                {
                    int i = _productAppService.InsertAndGetId(model); //新增
                    if (i > 0)
                    {
                        _result.Status = true;
                        _result.Message = i.ToString();
                    }
                }
                return new JsonResult() { Data = _result };
            }
            #endregion
    
            #region 修改商品
    
            [HttpGet]
            public ActionResult Update(int id)
            {
                var model = _productAppService.Get(id);
                return View(model);
            }
    
            [HttpPost]
            public ActionResult Update(Entitys.Product model)
            {
                _result.Status = false;
                //TODO:Convert to DTOs
                if (!ModelState.IsValid)
                {
                    _result.Message = ExpendErrors(this);
                }
                else
                {
                    var modelTarget = _productAppService.Get(model.Id); //赋值
                    modelTarget.ProductName = model.ProductName; //更新字段
                    modelTarget.Discontinued = model.Discontinued;
                    int i = _productAppService.InsertOrUpdateAndGetId(modelTarget); //新增
                    if (i > 0)
                    {
                        _result.Status = true;
                        _result.Message = i.ToString();
                    }
                }
                return new JsonResult() { Data = _result };
            }
    
            #endregion
    
            #region 批量新增商品
            /// <summary>
            /// 批量新增商品(启用工作单元)
            /// </summary>
            /// <returns></returns>
            public ActionResult AddProductbatch()
            {
                List<ProductInput> inputs = new List<ProductInput>();
                inputs.Add(new ProductInput
                {
                    ProductName = "新增的商品222",
                    SupplierID = 1,
                    CategoryID = 2,
                    Discontinued = true  //设置数据不符合  全部不提交
                });
                inputs.Add(new ProductInput
                {
                    ProductName = "新增的商品456",
                    SupplierID = 1,
                    CategoryID = 2,
                    Discontinued = false
                });
    
                _result.Status = false;
                StringBuilder builder = new StringBuilder();
    
                using (var unitOfWork = _unitOfWorkManager.Begin()) //启用工作单元
                {
                    try
                    {
                        foreach (var input in inputs)
                        {
                            //Convert to DTOs
                            var model = input.MapTo<Entitys.Product>();
                            _productAppService.InsertAndGetId(model); //新增
                        }
                        unitOfWork.Complete(); //提交事务
                    }
                    catch (Exception ex)
                    {
                        builder.AppendLine(ex.Message);
                    }
                }
                _result.Status = builder.Length == 0 ? true : false;
                _result.Message = builder.Length == 0 ? "" : builder.ToString();
                return new JsonResult() {Data = _result};
            }
            #endregion
    
            #region 删除商品
            /// <summary>
            /// 删除商品
            /// </summary>
            /// <param name="id">商品ID</param>
            /// <returns></returns>
            [HttpPost]
            public ActionResult Delete(int id)
            {
                _result.Status = false;
                //TODO:Convert to DTOs
                if (!ModelState.IsValid)
                {
                    _result.Message = ExpendErrors(this);
                }
                else
                {
                    try
                    {
                        _productAppService.Delete(id); //删除
                        _result.Status = true;
                    }
                    catch (Exception ex)
                    {
                        _result.Status = false;
                    }
                }
                return new JsonResult() { Data = _result };
            }
            #endregion
    
            #region 返回消息类
            /// <summary>
            /// 返回信息类
            /// </summary>
            public class StatusMsg
            {
                /// <summary>
                /// 返回状态 true false
                /// </summary>
                public bool Status;
                /// <summary>
                /// 返回信息 如400、401状态码或者其它信息
                /// </summary>
                public string Message;
                /// <summary>
                /// 返回扩展信息 
                /// </summary>
                public object Result;
            }
            #endregion
    
            #region 获取验证信息
            public static string ExpendErrors(Controller controller)
            {
                System.Text.StringBuilder sbErrors = new System.Text.StringBuilder();
                foreach (var item in controller.ModelState.Values)
                {
                    if (item.Errors.Count > 0)
                    {
                        for (int i = item.Errors.Count - 1; i >= 0; i--)
                        {
                            sbErrors.AppendLine(item.Errors[i].ErrorMessage);
                        }
                    }
                }
                return sbErrors.ToString();
            }
            #endregion
        }
    }



  • 相关阅读:
    js scrollTop到达指定位置!
    ajax图片加载,complete
    OpenShift 集群搭建指南
    net core ef code first 使用步骤
    Web Api Json 序列化 属性被加上 k__BackingField 解决办法
    [ASP.NET MVC 5 高级编程] 第4章 模型
    [ASP.NET MVC 5 高级编程] 第3章 视图
    [Java学习笔记] Java核心技术 卷1 第六章 接口与内部类
    [Java学习笔记] Java核心技术 卷1 第五章 继承
    [Java学习笔记] Java核心技术 卷1 第四章 对象与类
  • 原文地址:https://www.cnblogs.com/smartsmile/p/6234053.html
Copyright © 2020-2023  润新知