码迷,mamicode.com
首页 > 其他好文 > 详细

团队开发框架应用示例_01

时间:2016-04-14 15:55:09      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:

引用关系

Model

1 School.cs

ViewModel

2 SchoolDto.cs

3 AddSchoolViewModel.cs

4 EditSchoolViewModel.cs

BLL

5 ISchoolService.cs

6 SchoolService.cs

WebApi

7 PqaProfile.cs  CreateMap

8 UnityConfig.cs RegisterType

9 SchoolController.cs

Web

10 SchoolController.cs

12 School/Add.cshtml

13 School/Edit.cshtml

14 School/Index.cshtml

15 School/Info.cshtml

 

 

Relative URI

method

WebApi

Service

Route

/api/school

get

Get

schoolService.List

 

/api/school/GetInfo?id=id

get

GetInfo 

schoolService.Info

[Route("api/school/GetInfo")]

 

/api/school/

post

Post    

schoolService.Add

 

/api/school/id

put

Put     

schoolService.Edit

 

/api/school/ id

delete

Delete  

schoolService.LogicDel

 

 

 

Get      ->  schoolService.List(pageindex.Value, pagesize.Value, keyword, new ClaimHelper().UserID);

 

[Route("api/school/GetInfo")]

GetInfo  ->  schoolService.Info(id);

Post     ->  schoolService.Add(entity, new ClaimHelper().UserID);

Put      ->  schoolService.Edit(entity);

Delete   ->  schoolService.LogicDel(id);

数据库设计:

技术分享

Model

School.cs

using System;
using PPQA.Core.Data;

namespace PPQA.Model.Pqa
{
    public class School : EntityBase<Guid>
    {
        /// <summary>
        /// 学校名称
        /// </summary>
        public string SchoolName { get; set; }

        /// <summary>
        /// 所属教育局ID
        /// </summary>
        public Guid EdbId { get; set; }

        /// <summary>
        /// 状态值
        /// </summary>
        public int State { get; set; }

        /// <summary>
        /// 排序
        /// </summary>
        public int DisOrder { get; set; }

        /// <summary>
        /// 创建人ID
        /// </summary>
        public Guid CreateUserId { get; set; }

        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime CreateTime { get; set; }
    }
}

ViewModel

SchoolDto.cs

using System;

namespace PPQA.ViewModel.Pqa.Dtos
{
    public class SchoolDto
    {
        public Guid Id { get; set; }

        /// <summary>
        /// 学校名称
        /// </summary>
        public string SchoolName { get; set; }

        /// <summary>
        /// 所属教育局ID
        /// </summary>
        public Guid EdbId { get; set; }

        /// <summary>
        /// 状态值
        /// </summary>
        public int State { get; set; }

        /// <summary>
        /// 排序
        /// </summary>
        public int DisOrder { get; set; }

        /// <summary>
        /// 创建人ID
        /// </summary>
        public Guid CreateUserId { get; set; }

        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime CreateTime { get; set; }
    }
}

 

AddSchoolViewModel.cs

namespace PPQA.ViewModel.Pqa.ViewModels
{
    public class AddSchoolViewModel
    {
        /// <summary>
        /// 学校名称
        /// </summary>
        public string SchoolName { get; set; }
    }
}

 

EditSchoolViewModel.cs

using System;

namespace PPQA.ViewModel.Pqa.ViewModels
{
    public class EditSchoolViewModel : AddSchoolViewModel
    {
        // 只需传入ID
        public Guid Id { get; set; }
    }
}

 

BLL

ISchoolService.cs

using PPQA.ViewModel.Pqa.Dtos;
using PPQA.ViewModel.Pqa.ViewModels;
using System;

namespace PPQA.IBLL.Pqa
{
    public interface ISchoolService
    {
        Core.Data.EasyUiList List(int pageindex, int pagesize, string keyword, Guid userId);

        void LogicDel(Guid id);

        void Add(AddSchoolViewModel model, Guid userId);

        void Edit(EditSchoolViewModel model);

        SchoolDto Info(Guid id);
    }
}

 

SchoolService.cs

using System;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using PPQA.Core.Data;
using PPQA.Core.Erro;
using PPQA.Model.Pqa;
using PPQA.ViewModel.Pqa.Dtos;
using PPQA.ViewModel.Pqa.ViewModels;
using PPQA.DAL;
using PPQA.IBLL.Pqa;

namespace PPQA.BLL.Pqa
{
    public class SchoolService : ISchoolService
    {
        private DataBaseContext db;
        IUnitOfWork<DataBaseContext> unitWork;

        public SchoolService(DataBaseContext db, IUnitOfWork<DataBaseContext> unitWork)
        {
            this.db = db;
            this.unitWork = unitWork;
        }

        public void Add(AddSchoolViewModel model, Guid userId)
        {
            var entity = Mapper.Map<AddSchoolViewModel, School>(model);

            entity.Id = Guid.NewGuid();
            entity.SchoolName = model.SchoolName;
            entity.EdbId = Guid.NewGuid();     // 所属教育局ID,暂时设个默认值
            entity.State = 1;                  // 1 正常显示,0 逻辑删除
            entity.DisOrder = 9999;
            entity.CreateUserId = userId;
            entity.CreateTime = DateTime.Now;  // 后续建议改成取服务器时间

            db.Schools.Add(entity);
            unitWork.Commit();
        }

        public void Edit(EditSchoolViewModel model)
        {
            var entity = Mapper.Map<EditSchoolViewModel, School>(model);

            db.Set<School>().Attach(entity);

            var SetEntry = ((System.Data.Entity.Infrastructure.IObjectContextAdapter)db).ObjectContext.ObjectStateManager.GetObjectStateEntry(entity);
            Type type = typeof(EditSchoolViewModel);

            foreach (var item in type.GetProperties())
            {
                if ("EntityState" == item.Name || "EntityKey" == item.Name)
                {
                    continue;
                }
                SetEntry.SetModifiedProperty(item.Name);
            }
            unitWork.Commit();
        }

        public SchoolDto Info(Guid id)
        {
            var entity = db.Schools.FirstOrDefault(p => p.Id == id);
            if (entity == null)
                throw new dsDbException("数据验证错误", new List<Core.ValidateItem>() { new Core.ValidateItem() { ErrMessage = "记录不存在!" } });
            return Mapper.Map<School, SchoolDto>(entity);
        }

        public Core.Data.EasyUiList List(int pageindex, int pagesize, string keyword, Guid userId)
        {
            var q = db.Schools.Where(p => p.State == 1);
            if (!String.IsNullOrEmpty(keyword))
            {
                q = q.Where(p => p.SchoolName.Contains(keyword));
            }
            return new Core.Data.EasyUiList() { total = q.Count(), rows = Mapper.Map<List<School>, List<SchoolDto>>(q.OrderBy(p => p.DisOrder).Skip((pageindex - 1) * pagesize).Take(pagesize).ToList()) };
        }

        public void LogicDel(Guid id)
        {
            var entity = db.Schools.FirstOrDefault(p => p.Id == id);
            if (entity == null)
                throw new dsDbException("数据验证错误", new List<Core.ValidateItem>() { new Core.ValidateItem() { ErrMessage = "无法删除!" } });

            // state设为0,逻辑删除
            entity.State = 0;
            unitWork.Commit();
        }
    }
}

 

WebApi

AutoMapper-> Profiles->PqaProfile   

PqaProfile.cs

 CreateMap

 

#region School
CreateMap<School, SchoolDto>();
CreateMap<AddSchoolViewModel, School>();
CreateMap<EditSchoolViewModel, School>();
#endregion

 

App_Start->UnityConfig.cs

UnityConfig

container.RegisterType<ISchoolService, SchoolService>(new HierarchicalLifetimeManager());

SchoolController.cs

using PPQA.Core;
using PPQA.IBLL.Pqa;
using PPQA.ViewModel.Pqa.Dtos;
using PPQA.ViewModel.Pqa.ViewModels;
using PPQA.WebApi.Filters;
using System;
using System.Web.Http;

namespace PPQA.WebApi.Controllers
{
    [Authorize]
    [WebApiExceptionFilter]
    public class SchoolController : ApiController
    {
        private readonly ISchoolService schoolService;

        public SchoolController(ISchoolService schoolService)
        {
            this.schoolService = schoolService;
        }
        
        [PermissionFilter("school", (int)ActionEnum.Query)]
        public Core.Data.EasyUiList Get(int? pageindex, int? pagesize, string keyword)
        {
            if (!pageindex.HasValue) pageindex = 1;
            if (!pagesize.HasValue) pagesize = Core.Data.Pager.PageSize;
            // userId = new ClaimHelper().UserID
            return schoolService.List(pageindex.Value, pagesize.Value, keyword, new ClaimHelper().UserID);
        }

        [Route("api/school/GetInfo")]
        [PermissionFilter("school", (int)ActionEnum.Query)]
        public SchoolDto GetInfo(Guid id)
        {
            return schoolService.Info(id);
        }

        [PermissionFilter("school", (int)ActionEnum.Add)]
        public void Post([FromBody]AddSchoolViewModel entity)
        {
            schoolService.Add(entity, new ClaimHelper().UserID);
        }

        [PermissionFilter("school", (int)ActionEnum.Edit)]
        public void Put(Guid id, [FromBody]EditSchoolViewModel entity)
        {
            entity.Id = id;
            schoolService.Edit(entity);
        }

        [PermissionFilter("school", (int)ActionEnum.Del)]
        public void Delete(Guid id)
        {
            schoolService.LogicDel(id);
        }

    }
}

前端展现

SchoolController.cs

using System.Web.Mvc;

namespace PPQA.Web.Controllers
{
    public class SchoolController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

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

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

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

School/Add.cshtml

@{
    ViewBag.Title = "新增学校";
}
<div style="padding:10px 40px 20px 40px">
    <table cellpadding="5">
        <tr>
            <td>学校名称:</td>
            <td><input class="easyui-textbox" type="text" id="txtSchoolName" data-options="required:true" /></td>
        </tr>
    </table>

    <div style="text-align:center;padding:5px">
        <a href="javascript:void(0)" class="easyui-linkbutton" onclick="submitForm()">提 交</a>
    </div>
</div>

<script src="~/Scripts/layer/layer.js"></script>
<script>
    function submitForm() {
        var postdata = {};
        postdata.SchoolName = $("#txtSchoolName").textbox(getValue).trim();
        if (isEmpty(postdata.SchoolName)) {
            $.messager.alert(警告, 请输入学校名称!, info);
            return;
        }

        BoerAjax("/api/school/", postdata, "post", function () {
            top.window.frames["ContentFrame"].DataReLoad();
            top.$(#dd).dialog("close");
        });
    }
</script>

 


School/Edit.cshtml

@{
    ViewBag.Title = "编辑学校";
}

<div style="padding:10px 40px 20px 40px">
    <table cellpadding="5">
        <tr>
            <td>学校名称:</td>
            <td><input class="easyui-textbox" type="text" id="txtSchoolName" data-options="required:true" /></td>
        </tr>
    </table>

    <div style="text-align:center;padding:5px">
        <a href="javascript:void(0)" class="easyui-linkbutton" onclick="submitForm()">提 交</a>
    </div>
</div>


<input id="hiddenSchoolId" type="hidden" value="" />
<script src="~/Scripts/layer/layer.js"></script>
<script>
    function loadInfo() {
        var id = $("#hiddenSchoolId").val();
        if (id.isEmpty()) {
            $.messager.alert(警告, 未获取传入的信息!, info);
            return;
        }

        BoerAjax("/api/school/GetInfo?id=" + id, null, "get", function (data) {
            $("#txtSchoolName").textbox("setValue", data.SchoolName);
        });

    }

    function submitForm() {
        var id = $("#hiddenSchoolId").val();
        var postdata = {};
        postdata.SchoolName = $("#txtSchoolName").textbox(getValue).trim();
        postdata.DisOrder = 999;
        if (isEmpty(postdata.SchoolName)) {
            $.messager.alert(警告, 请输入学校姓名!, info);
            return;
        }
        BoerAjax("/api/school/" + id, postdata, "put", function () {
            top.window.frames["ContentFrame"].DataReLoad();
            $.messager.alert(警告, 保存成功!, info);
            setTimeout(function () {
                top.$(#dd).dialog("close");
            }, 1000);

        });
    }
</script>

 


School/Index.cshtml

@{
    ViewBag.Title = "学校列表";
}
<div id="toolbar">
    <div>
        <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-add" onclick="Add()" plain="true">新增学校</a>
        <label style="margin-left:20px">关键字:</label>
        <input id="txtKeyword" class="easyui-textbox" data-options="prompt:‘请输入学校‘" style="width:150px;height:25px" value="" />
        <a href="javascript:void(0)" class="easyui-linkbutton" onclick="searchInfo()" iconCls="icon-search">查询</a>
    </div>
</div>
<div id="dg">
</div>
<from id="myForm" enctype="application/x-www-form-urlencoded"></from>
<script src="~/Scripts/jquery-plugin/jquery.form.js"></script>
<script type="text/javascript">

    $(document).ready(function () {
        LoadData();
    });

    function LoadData() {
        var h = $(window).height();
        var dataGrid = $(#dg);
        var keyword = $("#txtKeyword").val();
        dataGrid.datagrid({
            idField: Id,
            title: 学校列表,
            autoRowHeight: false,
            loadMsg: "数据加载中,请稍候...",
            pageList: [50, 40, 30, 20, 10],
            pageSize: 10,
            striped: true,
            height: h,
            fitColumns: true,
            singleSelect: true,
            rownumbers: true,
            pagination: true,
            nowrap: false,
            showFooter: false,
            toolbar: #toolbar,
            columns: [[
                {
                    field: cz, title: 操作, width: 180, halign: center, align: center, fixed: true,
                    formatter: function (value, row, index) {
                        return <button type="button" class="btn btn-warning btn-xs" onclick="Edit(\‘ + row.Id + \‘)"><span class="glyphicon glyphicon-edit"></span>编辑</button> <button type="button" class="btn btn-danger btn-xs" onclick="Del(\‘ + row.Id + \‘,\‘ + row.SchoolName + \‘)"><span class="glyphicon glyphicon-remove"></span>删除</button>;
                    }
                }, {
                    field: SchoolName, title: 学校名称, width: 240, halign: center, align: left, fixed: true,
                    formatter: function (value, row, index) {
                        return value;
                    }
                }, {
                    field: CreateTime, title: 创建时间, width: 150, halign: center, align: center, fixed: true,
                    formatter: function (value, row, index) {
                        if (value != null) {
                            var d = new Date(value);
                            return d.format("yyyy-MM-dd HH:mm:ss");
                        } else {
                            return "";
                        }
                    }
                }
            ]]
        });

        dataGrid.datagrid(getPager).pagination({
            displayMsg: 当前显示从 [{from}] 到 [{to}] 共[{total}]条记录,
            onSelectPage: function (pPageIndex, pPageSize) {
                //改变opts.pageNumber和opts.pageSize的参数值,用于下次查询传给数据层查询指定页码的数据
                var ajaxdata = {};
                ajaxdata.pageindex = pPageIndex;
                ajaxdata.pagesize = pPageSize;
                ajaxdata.keyword = keyword;
                BoerAjax("/api/school", ajaxdata, "get", function (data) {
                    dataGrid.datagrid(loadData, data);
                });
            }
        });

        BoerAjax("/api/school", { pageindex: 1, pagesize: dataGrid.datagrid(getPager).data("pagination").options.pageSize, keyword: keyword }, "get", function (data) {
            dataGrid.datagrid(loadData, data);
        });
    }

    $(window).resize(function () {
        onResize();
    });

    function onResize() {
        $("#dg").height = $(window).height();
        $("#dg").datagrid("options").width = $(window).width();
        $("#dg").datagrid("resize");
    }

    function searchInfo() {
        BoerAjax("/api/school", { pageindex: 1, pagesize: $(#dg).datagrid(getPager).data("pagination").options.pageSize, keyword: $("#txtKeyword").val() }, "get", function (data) {
            $(#dg).datagrid(loadData, data);
        });
    }

    function Del(id, name) {
        $.messager.confirm(确定删除, 您确定要删除学校[ + name + ]吗?, function (r) {
            if (r) {
                BoerAjax("/api/school/" + id, null, "delete", function (data) {
                    DataReLoad();
                });
            }
        });
    }

    function Edit(id) {
        top.$(#dd).dialog({
            title: 编辑学校,
            width: 400,
            height: 250,
            closed: false,
            cache: false,
            iconCls: icon-edit,
            href: /school/Edit?id= + id,
            modal: true,
            onLoad: function () {
                top.$("#hiddenSchoolId").val(id);
                top.loadInfo();
            }
        }).dialog(center);
    }

    function Add() {
        top.$(#dd).dialog({
            title: 新增学校,
            width: 400,
            height: 250,
            closed: false,
            cache: false,
            iconCls: icon-add,
            href: /school/Add,
            modal: true
        }).dialog(center);
    }

    function DataReLoad() {
        $("#txtKeyword").val(‘‘);
        searchInfo();
    }

</script>

 


School/Info.cshtml

@model dynamic

@{
    ViewBag.Title = "title";
    Layout = "_Layout";
}

<h2>title</h2>

 

前端界面展现

技术分享

团队开发框架应用示例_01

标签:

原文地址:http://www.cnblogs.com/Bobby0322/p/5390962.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!