.net MVC 項目1

1、 前臺顯示動態數據的三種方式

一、kendo ui 的數據綁定

html 代碼

<div class="box box-solid">
    <div class="box-body">
        @(Html.Kendo().Grid<CompanyServiceModel>()
                                        .Name("grid")
                                        .Columns(columns =>
                                        {
                                            columns.Bound(c => c.ServiceName).Title("服務項目").HtmlAttributes(new { style = "white-space:nowrap;" });
                                            columns.Bound(c => c.SuitableFor).Title("適用人羣").HtmlAttributes(new { style = "white-space:nowrap;" });
                                            columns.Bound(c => c.OriginPrice).Title("原價").HtmlAttributes(new { style = "white-space:nowrap;" });
                                            columns.Bound(c => c.DiscountPrice).Title("折扣價").HtmlAttributes(new { style = "white-space:nowrap;" });
                                            columns.Bound(c => c.policy).Title("優惠政策").HtmlAttributes(new { style = "white-space:nowrap;" });
                                            columns.Bound(c => c.Id).Title("操做").Width(240)
                                            .ClientTemplate(
                                                @"<button class='k-button k-grid-delete' onclick='delService(" + "#:Id #" + ")'>刪除</button>" +
                                                "<button class='k-button k-grid-delete' id='showDialogBtn2' data-role='button' role='button' aria-disabled='false' tabindex='0' onclick='editService("+"#:Id #"+")'>編輯服務</button>")
                                                ;
                                        })
                                        .HtmlAttributes(new { style = "height:600px;" })
                                        .Pageable(p => p.PageSizes(new int[] { 20, 30, 50, 100 }).Refresh(true).Messages(model => model.ItemsPerPage("條/頁")))
                                        .Scrollable()
                                        .Resizable(f => f.Columns(true))
                                        .DataSource(dataSource => dataSource
                                            .Ajax()
                                            .PageSize(20)
                                            .Read(read => read.Action("GetCompanyServiceList2", "Company").Data("onDataBinding"))
                                        )
        )
    </div>
</div>

js 作數據綁定

$(function () {
        search();
    });
    var searchModel = {
    };
    function onDataBinding() {
        return searchModel;
    }
    function search() {
        searchModel = {
            "CompanyId": $("#Id").val()
        }
        var grid = $("#grid").data("kendoGrid");
        grid.dataSource.page(1);
    }

controller 方法

// GET: Company

        private ICompanyService CompanyService { get; set; }
        private ICompanyServiceService CompanyServiceService { get; set; }


        public CompanyController(ICompanyService companyService, ICompanyServiceService companyServiceService)
        {
            CompanyService = companyService;
            CompanyServiceService = companyServiceService;
        }
        /// <summary>
        /// 獲取公司服務列表kendo ui 用的
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ActionResult GetCompanyServiceList2([DataSourceRequest]DataSourceRequest request, CompanyServiceSearchModel model)
        {
            SearchModel searchModel = new SearchModel()
            {
                PageNo = request.Page,
                PageSize = request.PageSize
            }; ;
            searchModel.Filters = model.ToFilters();
            searchModel.Sorts = model.ToSorts();
            ApiListResult<CompanyServiceModel> apiListResult = CompanyServiceService.Search(searchModel);

            return Json(apiListResult.ToDataSourceResult());
        }

注意:返回的是:Json(apiListResult.ToDataSourceResult());javascript

2.Ajax 數據綁定

html 代碼

<!--人事服務-->
        <div class="company-service" id="human-resource">
            <div class="category-item">
                <div class="catagory-name">人事服務</div>
                <div class="catagory-desc">(提供專業的人力資源,社保、公積金開戶及管理代繳服務,人事外包服務,員工福利等)</div>
            </div>
            <div class="company-list" id="human-resource-companies">
            </div>
        </div>

        <!--財務服務-->
        <div class="company-service" id="fiance-service">
            <div class="category-item">
                <div class="catagory-name">財務服務</div>
                <div class="catagory-desc">(提供全方位的、專業化的財稅服務,解決企業財務、稅務、工商、年檢等各種「疑難雜症」,有效的幫助企業節省時間、經理和資金)</div>
            </div>
            <div class="company-list" id="fiance-service-companies">
            </div>
        </div>

根據id 作html 的拼接css

js 作數據獲取,拼接html

<script type="text/javascript">
//服務商數據獲取 
$(function () {
        $.ajax({
            type: "post",  //提交方式
            dataType: "json", //數據類型
            //data: JSON.stringify(jsonIds),//{ItemType: $("#itemType").val().trim()}自定義數據參數,視狀況添加
            url: '/Company/GetList', //請求url
            async: false,
            contentType: "application/json",
            success: function (json_data) {
                json_data.forEach(function (item) {
                    if (item['ServiceCategory'] == "人事服務")
                    {
                        $("#human-resource-companies").append(
                            '<a href="/company/detail/' + item['Id'] +'" data-toggle="modal" data-target="#modal" >'
                            +'<div class="card-item-outer ">'
                            + '<div class="card-item">'
                            + '<div class="card-img">'
                            + '<img src="' + item['ImageUrl'] + '" alt="' + item['CompanyName'] + 'image">'
                            + '</div >'
                            + '<div class="card-content">'
                            + '<span class="card-company-name">' + item['CompanyName'] + '</span>'
                            + '<ul class="service-info" id ="CompanyId' + item['Id']+'">'
                            + '</ul>'
                            + '</div>'
                            + '</div>'
                            + '</div>'
                            +'</a>');
                        getCompanyService(item['Id']);
                    }
                    else  (item['ServiceCategory'] == "財務服務") {
                        $("#fiance-service-companies").append(
                            '<a href="/company/detail/' + item['Id'] + '" data-toggle="modal" data-target="#modal" >'
                            + '<div class="card-item-outer ">'
                            + '<div class="card-item">'
                            + '<div class="card-img">'
                            + '<img src="' + item['ImageUrl'] + '" alt="' + item['CompanyName'] + 'image">'
                            + '</div >'
                            + '<div class="card-content">'
                            + '<span class="card-company-name">' + item['CompanyName'] + '</span>'
                            + '<ul class="service-info" id ="CompanyId' + item['Id'] + '">'
                            + '</ul>'
                            + '</div>'
                            + '</div>'
                            + '</div>'
                            + '</a>');
                        getCompanyService(item['Id']);
                    }
               });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(XMLHttpRequest.responseText);
            }
        })
    })
    //服務項目數據獲取
    function getCompanyService(id) {
        var jsonCompanyId = eval('(' + '{"CompanyId":"' +  id+ '"}' + ')');
        $.ajax({
            type: "post",  //提交方式
            dataType: "json", //數據類型
            //data: JSON.stringify(jsonIds),//{ItemType: $("#itemType").val().trim()}自定義數據參數,視狀況添加
            url: '/Company/GetCompanyServiceList', //請求url
            async: false,
            contentType: "application/json",
            data: JSON.stringify(jsonCompanyId),
            success: function (json_data) {
                json_data.forEach(function (item) {
                    $("#CompanyId" + id).after(
                        '<li style="font-size: 12px;color: rgba(0, 0, 0, 0.43); list-style: none;">' + item['ServiceName'] + '</li>'
                    );

                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(XMLHttpRequest.responseText);
            }
        });
    }

</script>

這裏作了兩次ajax 獲取數據,一個是Company ,一個是CompanyServicehtml

Controller 代碼

public class CompanyController : Controller
    {
        // GET: Company

        private ICompanyService CompanyService { get; set; }
        private ICompanyServiceService CompanyServiceService { get; set; }


        public CompanyController(ICompanyService companyService, ICompanyServiceService companyServiceService)
        {
            CompanyService = companyService;
            CompanyServiceService = companyServiceService;
        }

        #region 公司列表
        [CustomAuthorize("CompanyPage")]
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 獲取列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ActionResult GetList([DataSourceRequest]DataSourceRequest request, CompanySearchModel model)
        {
            SearchModel searchModel = new SearchModel();
            searchModel.Filters = model.ToFilters();
            searchModel.Sorts = model.ToSorts();
            ApiListResult<CompanyModel> apiListResult = CompanyService.Search(searchModel);

            return Json(apiListResult.Result);
        }

        /// <summary>
        /// 獲取公司服務列表ajax 用的
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ActionResult GetCompanyServiceList([DataSourceRequest]DataSourceRequest request, CompanyServiceSearchModel model)
        {
            SearchModel searchModel = new SearchModel();
            searchModel.Filters = model.ToFilters();
            searchModel.Sorts = model.ToSorts();
            ApiListResult<CompanyServiceModel> apiListResult = CompanyServiceService.Search(searchModel);

            return Json(apiListResult.Result);
        }
    }

Razor 標籤語言

傳出來的是model 或者model list ,相似c#同樣遍歷數據前端

html 代碼

@model CompanyModel
@{
    Layout = null;
    ViewBag.Title = "服務商詳情";
}

<div class="company-body" id="company-body" style="padding: 10px; background-color:#ecf0f5;" >
        <div class="company-body-loading" style="position: relative;">
            <!--第一個卡板-->
            <div class="company-base-card">
                <div class="company-card-title">
                    服務商信息
                    <hr  style="margin-top: 5px;"/>
                </div>
                <div class="company-detail-info">
                    <div class="company-detail-left-info">
                        <div class="name">
                            @Model.CompanyName
                            <span class="text-primary">
                                (@Model.ServiceCategory)
                            </span>
                        </div>
                        <div class="desc">
                            @Model.Introduction
                        </div>
                    </div>
                    <input type="text" id="ModelId" value="@Model.Id" style="display:none"/>
                    <input type="text" id="CompanyName" value="@Model.CompanyName" style="display:none"/>
                    <div class="company-detail-right-logo">
                        <div class="card-img" id="image" >
                            <img id="Image"  src="@Model.ImageUrl"/>
                        </div>
                    </div>
                </div>
            </div>

            <!--第二個卡板-->
            <div class="company-base-card">
                <div class="company-card-title">
                    申請及諮詢方式
                    <hr style="margin-top: 5px;" />
                </div>
                <div class="company-detail-info">
                    <div class="contact-mode">
                        <div class="mode-item">
                            <div class="left-lable">諮詢電話:</div>
                            @if (Model.Tel.Length > 0)
                            {
                                <div class="flex-item">@Model.Tel</div>
                            }
                            else
                            {
                                <div class="flex-item">-</div>
                            }
                        </div>
                        <div class="mode-item">
                            <div class="left-lable">官網:</div>
                            @if (!string.IsNullOrEmpty(@Model.Website))
                            {
                                <div class="flex-item">@Model.Website</div>
                            }
                            else
                            {
                                <div class="flex-item">-</div>
                            }
                        </div>
                        <div class="mode-item">
                            <div class="left-lable">郵箱:</div>
                            @if (!string.IsNullOrEmpty(@Model.Email))
                            {
                                <div class="flex-item">@Model.Email</div>
                            }
                            else
                            {
                                <div class="flex-item">-</div>
                            }
                        </div>
                    </div>
                </div>
            </div>

            <!--第三個卡板-->
            <div class="company-base-card">
                <div class="company-card-title">
                    服務項目
                    <hr style="margin-top: 5px;" />
                </div>
                <div class="company-detail-info">
                    <div class="service-list">
                        @foreach (var x in Model.CompanyServices)
                        {
                            <div class="service-item">
                                <div class="service-item-left">
                                    <div class="name">@x.ServiceName</div>
                                    <div class="mode-item">
                                        <div class="left-lable">使用人羣:</div>
                                        <div class="flex-item">@x.SuitableFor</div>
                                    </div>
                                    <div class="mode-item">
                                        <div class="left-lable" style="color: #f8ab3c;">優惠政策:</div>
                                        <div class="flex-item" style="color: #f8ab3c;">@x.policy</div>
                                    </div>
                                </div>
                                <div class="service-item-right">
                                    @if (!string.IsNullOrWhiteSpace(x.OriginPrice) && !string.IsNullOrWhiteSpace(x.DiscountPrice))
                                    {
                                        <div class="text-danger" style="color: #f04134;">@x.DiscountPrice</div>
                                        <div class="original-price" style="text-decoration: line-through;">@x.OriginPrice</div>
                                    }
                                    else if (!string.IsNullOrWhiteSpace(x.OriginPrice) && string.IsNullOrWhiteSpace(x.DiscountPrice))
                                    {
                                        <div>-</div>
                                        <div class="original-price">@x.OriginPrice</div>
                                    }
                                    else if (string.IsNullOrWhiteSpace(x.OriginPrice) && !string.IsNullOrWhiteSpace(x.DiscountPrice))
                                    {
                                        <div class="text-danger" style="color: #f04134;">@x.DiscountPrice</div>
                                        <div class="original-price">-</div>
                                    }
                                    else
                                    {
                                        <div>-</div>
                                        <div>-</div>
                                    }
                                </div>

                            </div>

                        }

                    </div>
                </div>
            </div>

            
        </div>

    </div>

Controller 代碼

#region 詳情頁
        [HttpGet]
        public ActionResult Detail(int id)
        {
            CompanyModel viewModel = CompanyService.GetById(id).Result;
            return View(viewModel);
        }
        #endregion

2、彈窗

1.kendo UI 彈窗

html 代碼

<button class='k-button k-grid-delete' id='showDialogBtn2' data-role='button' role='button' aria-disabled='false' tabindex='0' onclick='editService("1")'>編輯服務</button>


<!--編輯彈窗-->
<div class="box box-solid" id="example2" style="display:none;">
</div>

1. editService("1") js 方法,並傳入一個參數 ,原來的方法是有kendo ui 的動態數據onclick='editService("+"#:Id #"+")'  java

2. id='showDialogBtn2' 這個id 能夠隨意設置jquery

3.彈窗的內容會設置在 id=「example2」 的div 中間web

JS 代碼

function editService(id) {
        $("#example2").kendoWindow({
            title: "服務項目",
            width: 500,
            content: "/Company/EditService/" + id,
            actions: [
                "Close"
            ],
            modal: true
        });

Controller 代碼 

/// <summary>
        /// 彈窗修改服務項目
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult EditService(int id)
        {
            CompanyServiceModel companyServiceModel = CompanyServiceService.GetById(id).Result; ;
            return View(companyServiceModel);
        }

跳轉頁面,並傳一個model 的方法ajax

另一個html 內容根據實際自行編輯數據庫

2. bootstrap 彈窗

html 代碼

<style>
    /*左邊或者右邊彈出框 的css 樣式*/
    .mybtn {
        position: fixed;
        right: 10px;
        bottom: 20px;
        display: block;
        width: 50px;
        height: 50px;
        border-radius: 50px;
        padding: 0px;
        text-align: center;
        line-height: 50px;
    }

    .modal.left .modal-dialog,
    .modal.right .modal-dialog {
        top: 140px;
        bottom: 0px;
        width: 770px;
        position: fixed;
        margin: auto;
        height: 100%;
        -webkit-transform: translate3d(0%, 0, 0);
        -ms-transform: translate3d(0%, 0, 0);
        -o-transform: translate3d(0%, 0, 0);
        transform: translate3d(0%, 0, 0);
        box-shadow: 0 7px 21px rgba(0,0,0,.3);
    }

    .modal.left .modal-content, .modal.right .modal-content {
        height: 100%;
        overflow-y: auto;
    }

    .modal.left .modal-body,
    .modal.right .modal-body {
        padding: 15px 15px 80px;
    }

    /*Left*/
    .modal.left.fade .modal-dialog {
        left: -320px;
        -webkit-transition: opacity 0.3s linear, left 0.3s ease-out;
        -moz-transition: opacity 0.3s linear, left 0.3s ease-out;
        -o-transition: opacity 0.3s linear, left 0.3s ease-out;
        transition: opacity 0.3s linear, left 0.3s ease-out;
    }

    .modal.left.fade.in .modal-dialog {
        left: 0;
    }

    /*Right*/
    .modal.right.fade .modal-dialog {
        right: -320px;
        -webkit-transition: opacity 0.3s linear, right 0.3s ease-out;
        -moz-transition: opacity 0.3s linear, right 0.3s ease-out;
        -o-transition: opacity 0.3s linear, right 0.3s ease-out;
        transition: opacity 0.3s linear, right 0.3s ease-out;
    }

    .modal.right.fade.in .modal-dialog {
        right: 0;
    }

    /* ----- 右邊彈窗背景不是灰色 ----- */
    #modal .modal-dialog.modal-content {
        border-radius: 0;
        border: none;
    }

    #modal .modal-dialog.modal-content.modal-header {
        border-bottom-color: #EEEEEE;
        background-color: #FAFAFA;
    }

    #modal .modal-backdrop {
        opacity: 0 !important;
        filter: alpha(opacity=0) !important;
    }
    /* ----- 右邊彈窗背景不是灰色 ----- */

</style>

<!--彈窗到其餘網頁的a標籤-->
<a href="/company/detail/1" data-toggle="modal" data-target="#modal" >彈窗</a>


<!--右邊Detail彈窗-->
<div class="modal right fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="modal" style="background-color: rgba(0, 0, 0, 0);">
    <div class="modal-dialog" role="document" >
        <div class="modal-content">
            <!--Detail/id 內容加載在這裏面-->
        </div>
        
    </div>
</div>
<!--右邊Detail彈窗-->

並須要在header 裏面引入對應的bootstrap 模態框的css js json

<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css">
	<script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
	<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

JS 代碼

<!--清除彈窗數據-->

    $("#modal").on("hidden.bs.modal", function () {
        $(this).removeData("bs.modal");
    });

bootstrap 的彈窗數據不會再關閉彈窗後消失,因此須要添加清空數據的js

Controller 代碼

#region 詳情頁
        [HttpGet]
        public ActionResult Detail(int id)
        {
            CompanyModel viewModel = CompanyService.GetById(id).Result;
            return View(viewModel);
        }
        #endregion

打開的彈窗內容的html

<div class="company-close" style="width: 18px; height: 18px; border-radius: 18px;display: inline-block;box-sizing: border-box;" aria-label="Close" data-dismiss="modal" >
                <i class="k-icon k-i-logout"></i>
            </div>

這個是關閉彈窗的功能鍵

 

3、圖片上傳

一、ajaxfileupload  

html 代碼

引入jquery 和 ajasfileupload 的js 

<script src="@Url.Content("~/Scripts/kendo/2017.3.1026/jquery.min.js")"></script>
<script src="~/Scripts/ajaxfileupload.js"></script>

頁面的圖片輸入框和顯示框

<style>
        #oDiv {
            height: 129px;
            width: 329px;
            border: 1px solid #000;
            text-align: center;
            margin-bottom: 10px;
        }
</style>

                            <div class="col-sm-8">
                                <div class="all">
                                    <div id="oDiv">
                                        <img src="~/Content/images/companies/1.jpg" id="showPic" style="height:100%;width:100%" />
                                    </div>
                                    <input type="file"  id="oInput" name="file" onchange="upload_cover(this)" placeholder="上傳圖片"/>
                                    <input type="text" id="ImageUrl" name="ImageUrl" placeholder="上傳圖片後顯示實際路徑" value="~/Content/images/companies/1.jpg"  style="display:none" />
                                </div>  
                            </div>

js 代碼

function upload_cover(obj) {
        //回傳後綴
        var filePath = $("input[name='file']").val();
        var extStart = filePath.lastIndexOf(".");
        var ext = filePath.substring(extStart, filePath.length).toUpperCase();

        ajax_upload(obj.id, function (data) { //function(data)是上傳圖片的成功後的回調方法
            var isrc = data.relatPath.replace(/\/\//g, '/'); //獲取的圖片的絕對路徑
            $('#image').attr('src', basePath + isrc).data('img-src', isrc); //給<input>的src賦值去顯示圖片
        }, ext);
    }

    //具體的上傳圖片方法
    function ajax_upload(feid, callback, ext) {
        if (image_check(feid)) {
            $.ajaxFileUpload({
                url: "/Company/UploadImage",
                secureuri: false,
                fileElementId: feid,
                dataType: 'json',
                data: {fileType: ext},//增長推送的屬性
                type: 'post',
                async: true,
                secureuri: false,
                success:
                function (data) {
                    alert(data.imagePath);
                    $("#ImageUrl").val(data.imagePath);
                    $("#showPic").attr("src", data.imagePath);
                },
                error:
                function (data) {
                    alert(data);
                }
            });
        }
        };
        function image_check(feid) { //本身添加的文件後綴名的驗證
            var img = document.getElementById(feid);
            return /.(jpg|png|gif|bmp)$/.test(img.value) ? true : (function () {
                modals.info('圖片格式僅支持jpg、png、gif、bmp格式,且區分大小寫。');
                return false;
            })();
        }

回傳成功後,會接收後臺傳上來的url相對路徑,並把路徑賦值到隱藏的input窗口,表單提交的時候就就能夠一同提交圖片的路徑

controller 代碼

#region  圖片上傳
        /// <summary>
        /// 圖片上傳控件
        /// </summary>
        /// <param name="fileNames"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UploadImage(HttpPostedFileBase file)
        {
            //獲取圖片後綴
            string fileType = Request.Form["fileType"];
            // 時間
            string now =  DateTime.Now.ToString("yyyyMMddHHmmssffff");
            //文件存放的文件路徑
            string folder = HttpContext.Server.MapPath("/Content/images/companies/");

            // 保存文件
            string filePath = Path.Combine(folder, now + fileType);
            file.SaveAs(filePath);
            //切出相對路徑
            string subFilePath = filePath.Substring(filePath.LastIndexOf("\\Content"));
            JsonResult json = new JsonResult();
            json.ContentType = "text/html";
            json.Data = new { imagePath = subFilePath, success = true };

            return json;
            //return Content(filePath);
        }
        #endregion

須要注意:

前端錄入文件的input 的 name=」file「 ,必定要和 controller 裏面的接收的參數 HttpPostedFileBase file 後面的file 名字是同樣的

4、auto mapping

框架裏面的讀寫分離,數據層的 entity 是和數據交接的類,服務層 viewmodel 是前端顯示的動態數據,當前端post 一個viewmodel 到服務層的額時候,適用auto mapping 就不須要一個個屬性作對接,viewmodel=》entity 的屬性對接

例如Create

public virtual ApiResult<TViewModel> Create<TViewModel>(TViewModel model, Action<TEntity> action)
        {
            TEntity entity = Mapper.Map<TEntity>(model);
            action(entity);
            _context.Set<TEntity>().Add(entity);

            bool isSaved = false;
            try
            {
                isSaved = _context.SaveChanges() > 0;
            }
            catch (DbEntityValidationException exception)
            {
                var errorMessages =
                    exception.EntityValidationErrors
                        .SelectMany(validationResult => validationResult.ValidationErrors)
                        .Select(m => m.ErrorMessage);

                var fullErrorMessage = string.Join(", ", errorMessages);
                //記錄日誌
                //Log.Error(fullErrorMessage);
                var exceptionMessage = string.Concat(exception.Message, " 驗證異常消息是:", fullErrorMessage);

                throw new DbEntityValidationException(exceptionMessage, exception.EntityValidationErrors);
            }

            if (!isSaved)
            {
                return ApiResult<TViewModel>.Error("新增記錄失敗!");
            }

            var result = _context.Set<TEntity>().ProjectToFirst<TEntity, TViewModel>(p => p.Id.Equals(entity.Id));
            return new ApiResult<TViewModel>()
            {
                Result = result
            };
        }

保存的時候只須要

TEntity entity = Mapper.Map<TEntity>(model);

就能夠經過字段名和屬性一一匹配,不須要寫匹配,只須要寫一個格式轉換的profile 

using AutoMapper;
using SP.Data;
using SP.Models.ViewModels;
using SP.WorkerLoan2.Models.Response;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SP.Services.Impl.Extensions.Profiles
{
    public class CompanyProfile : Profile
    {
        public CompanyProfile()
        {
            CreateMap<CompanyResponse, CompanyModel>();
            CreateMap<SP.Data.Company, CompanyModel>();
            CreateMap<CompanyModel, SP.Data.Company>()
                .ForMember(p => p.CreatedTime, opt => opt.Ignore())
                .ForMember(p => p.CreatedBy, opt => opt.Ignore());
        }
    }
}

其中。Ignore 的屬性是表示entity屬性值不會匹配viewmodel的,這樣,就能夠對於部分字段作邏輯更新;

在調用 Create<TViewModel>(TViewModel model, Action<TEntity> action)

/// <summary>
        /// 新增
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public override ApiResult<CompanyModel> Create(CompanyModel model)
        {

            return Create<CompanyModel>(model, entity =>
            {
                entity.IsDeleted = false;
                entity.CreatedTime = DateTime.Now;
                entity.CreatedBy = model.CreatedBy;
                entity.UpdatedTime = DateTime.Now;
                entity.UpdatedBy = model.UpdatedBy;
            });
        }

手動上部分須要匹配的內容便可。

5、枚舉值

建立枚舉值的類

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SP.Infrastructure.Enums
{
    /// <summary>
    /// 客戶類型枚舉
    /// </summary>
    public enum CustomerType
    {
        /// <summary>
        /// 意向客戶
        /// </summary>
        [Display(Name = "意向客戶")]
        Intention = 1,

        /// <summary>
        /// 成交客戶
        /// </summary>
        [Display(Name = "成交客戶")]
        Deal = 2,
        /// <summary>
        /// 流失客戶
        /// </summary>
        [Display(Name = "流失客戶")]
        Loss = 3
    }
}

其中, Intention = 1, 左邊是model 或者entity 的 CustomerType 的值,右邊 1 是數據庫保存的值

public class Customer : BaseEntity
    {

        /// <summary>
        /// 客戶類型
        /// </summary>
        public CustomerType CustomerType { get; set; }
     }

建立類的時候,using 枚舉值的類就能夠直接使用

前端顯示和更改的時候

<div class="form-group">
                        @Html.Label("CustomerType", "客戶類型:", new { @class = "col-sm-2 control-label" })
                        <div class="col-sm-8">
                            @(Html.Kendo().DropDownList().Name("CustomerType")
                            .BindTo(new List<SelectListItem>() {
                                new SelectListItem(){Text="意向客戶",Value="Intention"},
                                new SelectListItem(){Text="成交客戶",Value="Deal"},
                                new SelectListItem(){Text="流失客戶",Value="Loss"}
                            }).Value(Model.CustomerType.ToString())
                            .HtmlAttributes(new { placeholder = "請選擇客戶類型", style = "width:100%;", type = "text" }))
                        </div>
                    </div>

注意:

一、Value 爲 model 的值,Text 是 前端顯示選擇的值,

二、Model.CustomerType.ToString() 顯示數據的是須要ToString顯示,若是字段類型不是枚舉值就就直接顯示Model.CustomerType 便可

6、一對多關係code first 兩表關聯

如 : company 裏面有多個 companyservice ,companyservice 裏面只有一個company ,並經過外鍵companyId 關聯

Company

namespace SP.Data
{

    /// <summary>
    /// 服務市場的公司
    /// </summary>
    public class Company : BaseEntity
    {
        /// <summary>
        /// 公司名字
        /// </summary>
        public string CompanyName { get; set; }

         /// <summary>
        /// 公司服務
        /// </summary>
        public virtual List<CompanyService> CompanyServices { get; set; }
    }
}

CompanyService

namespace SP.Data
{
    public class CompanyService : BaseEntity
    {

        /// <summary>
        /// 服務項目
        /// </summary>
        public int? CompanyId { get; set; }

        /// <summary>
        /// 服務項目
        /// </summary>
        public string ServiceName { get; set; }

        /// <summary>
        /// 所屬公司
        /// </summary>
        public virtual Company Company { get; set; }
    }
}

 

在作mapping的時候

CompanyMap 只須要寫本身那部分的內容

而CompanyServiceMap

namespace SP.Data.Mapping
{
    public class CompanyServiceMap : BaseEntityTypeConfiguration<CompanyService>
    {
        public CompanyServiceMap()
        {
            this.ToTable("CompanyService");
            this.HasKey(p => p.Id);

            this.Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
            this.Property(p => p.ServiceName).HasMaxLength(500);
            this.HasRequired(p => p.Company);
        }
    }
}

系統會自動識別出CompanyId 爲外鍵,

若是另外在CompanyServiceMap 裏面,設置手工寫一個外鍵上去,系統會也會自動幫你建立一個,數據庫的company_id 的字段,致使一共有兩個 同樣的字段兩個外鍵

相關文章
相關標籤/搜索