構建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系統(9)-MVC與EasyUI結合增刪改查


系列目錄

文章於2016-12-17日重寫

在第八講中,我們已經做到了怎么樣分頁。這一講主要講增刪改查。第六講的代碼已經給出,里面包含了增刪改,大家可以下載下來看下。

這講主要是,制作漂亮的工具欄,雖然easyui的datagrid已經自帶可以設置工具欄,我們還是要提取出來,為以后權限控制做更好的准備。

先看一張界面調整后的效果圖

大家只要加入以下HTML代碼到index上就可以了

<div class="mvctool">
<input id="txtQuery" type="text" class="searchText">
<a id="btnQuery" style="float: left;" class="l-btn l-btn-plain"><span class="l-btn-left"><span class="l-btn-text icon-search" style="padding-left: 20px;">查詢</span></span></a><div class="datagrid-btn-separator"></div>
<a id="btnCreate" style="float: left;" class="l-btn l-btn-plain"><span class="l-btn-left"><span class="l-btn-text icon-add" style="padding-left: 20px;">新增</span></span></a><div class="datagrid-btn-separator"></div>
<a id="btnEdit" style="float: left;" class="l-btn l-btn-plain"><span class="l-btn-left"><span class="l-btn-text icon-edit" style="padding-left: 20px;">編輯</span></span></a><div class="datagrid-btn-separator"></div>
<a id="btnDetails" style="float: left;" class="l-btn l-btn-plain"><span class="l-btn-left"><span class="l-btn-text icon-details" style="padding-left: 20px;">詳細</span></span></a><div class="datagrid-btn-separator"></div>
<a id="btnDelete" style="float: left;" class="l-btn l-btn-plain"><span class="l-btn-left"><span class="l-btn-text icon-remove" style="padding-left: 20px;">刪除</span></span></a><div class="datagrid-btn-separator"></div>
<a id="btnExport" style="float: left;" class="l-btn l-btn-plain"><span class="l-btn-left"><span class="l-btn-text icon-export" style="padding-left: 20px;">導出</span></span></a>
<a id="btnReload" style="float: left;" class="l-btn l-btn-plain"><span class="l-btn-left"><span class="l-btn-text icon-reload" style="padding-left: 20px;">刷新</span></span></a>
</div>
View Code

有能力的朋友再優化一下樣式

好,我們用jquery為按鈕添加事件。增、刪、改、查,把導出和刷新刪掉吧。沒用到

在index加入以下代碼js代碼

<script type="text/javascript">

    //ifram 返回
    function frameReturnByClose() {
        $("#modalwindow").window('close');
    }
    //iframe 返回並刷新
    function frameReturnByReload(flag) {
        if (flag)
            $("#List").datagrid('load');
        else
            $("#List").datagrid('reload');
    }
    //輸出信息
    function frameReturnByMes(mes) {
        $.messageBox5s('提示', mes);
    }
    $(function () {
      
        $("#btnCreate").click(function () {
            $("#modalwindow").html("<iframe width='100%' height='98%' scrolling='no' frameborder='0'' src='/SysSample/Create'></iframe>");
            $("#modalwindow").window({ title: '新增', width: 700, height: 400, iconCls: 'icon-add' }).window('open');
        });
        $("#btnEdit").click(function () {
            var row = $('#List').datagrid('getSelected');
            if (row != null) {
                $("#modalwindow").html("<iframe width='100%' height='99%'  frameborder='0' src='/SysSample/Edit?id=" + row.Id + "&Ieguid=" + GetGuid() + "'></iframe>");
                $("#modalwindow").window({ title: '編輯', width: 700, height: 430, iconCls: 'icon-edit' }).window('open');
            } else { $.messageBox5s('提示', '請選擇要操作的記錄'); }
        });
        $("#btnDetails").click(function () {
            var row = $('#List').datagrid('getSelected');
            if (row != null) {

                $("#modalwindow").html("<iframe width='100%' height='98%' scrolling='no' frameborder='0' src='/SysSample/Details?id=" + row.Id + "&Ieguid=" + GetGuid() + "'></iframe>");
                $("#modalwindow").window({ title: '詳細', width: 500, height: 300, iconCls: 'icon-details' }).window('open');
            } else { $.messageBox5s('提示', '請選擇要操作的記錄'); }
            });
        $("#btnQuery").click(function () {
            var queryStr = $("#txtQuery").val();
            //如果查詢條件為空默認查詢全部
            if (queryStr == null) {
                queryStr = "%";
            }
            $('#List').datagrid({
                url: '/SysSample/GetList?queryStr=' + encodeURI(queryStr)
            });

        });
        $("#btnDelete").click(function () {
            var row = $('#List').datagrid('getSelected');
            if (row != null) {
                $.messager.confirm('提示', '確定刪除', function (r) {
                        if (r) {
                            $.post("/SysSample/Delete?id=" + row.Id, function (data) {
                                if (data.type == 1)
                                    $("#List").datagrid('load');
                                $.messageBox5s('提示', data.message);
                            }, "json");

                        }
                    });
            } else { $.messageBox5s('提示', '請選擇要操作的記錄'); }
            });
    });
</script>
View Code

 

里面用到了easyui 的window

所以我們在Index頂部加入一個層來包含彈出window,我們把增加,修改的視圖放在iframe里面,然后附加到window里面彈出

<div id="modalwindow" class="easyui-window" data-options="modal:true,closed:true,minimizable:false,shadow:false"></div>

<div class="mvctool">................

關於$.messageBox5s是我擴展easyui的message控件的結果,擴展如下

/** 
* 在iframe中調用,在父窗口中出提示框(herf方式不用調父窗口)
*/
$.extend({
    messageBox5s: function (title, msg) {
        $.messager.show({
            title: title, msg: msg, timeout: 5000, showType: 'slide', style: {
                left: '',
                right: 5,
                top: '',
                bottom: -document.body.scrollTop - document.documentElement.scrollTop+5
            }
        });
    }
});
$.extend({
    messageBox10s: function (title, msg) {
        $.messager.show({
            title: title, msg: msg, height: 'auto', width: 'auto', timeout: 10000, showType: 'slide', style: {
                left: '',
                right: 5,
                top: '',
                bottom: -document.body.scrollTop - document.documentElement.scrollTop + 5
            }
        });
    }
});
$.extend({
    show_alert: function (strTitle, strMsg) {
        $.messager.alert(strTitle, strMsg);
    }
});

/** 
* panel關閉時回收內存,主要用於layout使用iframe嵌入網頁時的內存泄漏問題
*/
$.fn.panel.defaults.onBeforeDestroy = function () {

    var frame = $('iframe', this);
    try {
        // alert('銷毀,清理內存');
        if (frame.length > 0) {
            for (var i = 0; i < frame.length; i++) {
                frame[i].contentWindow.document.write('');
                frame[i].contentWindow.close();
            }
            frame.remove();
            if ($.browser.msie) {
                CollectGarbage();
            }
        }
    } catch (e) {
    }
};
jquery.easyui.plus.js

創建jquery.easyui.plus.js放到scripts目錄下,引入即可

編譯預覽一下,點擊下,新增和編輯,好,有效果了

此時我們創建增加,和編輯的action和view

這里是SysSampleController的代碼

using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using App.Common;
using App.IBLL;
using App.Models.Sys;
using Microsoft.Practices.Unity;


namespace App.Admin.Controllers
{
    public class SysSampleController :Controller
    {

        /// <summary>
        /// 業務層注入
        /// </summary>
        [Dependency]
        public ISysSampleBLL m_BLL { get; set; }
        public ActionResult Index()
        {

            return View();
        }
        public JsonResult GetList(GridPager pager, string queryStr)
        {
            List<SysSampleModel> list = m_BLL.GetList(ref pager);
            var json = new
            {
                total = pager.totalRows,
                rows = (from r in list
                        select new SysSampleModel()
                        {

                            Id = r.Id,
                            Name = r.Name,
                            Age = r.Age,
                            Bir = r.Bir,
                            Photo = r.Photo,
                            Note = r.Note,
                            CreateTime = r.CreateTime,

                        }).ToArray()

            };

            return Json(json, JsonRequestBehavior.AllowGet);
        }

        #region 創建
        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public JsonResult Create(SysSampleModel model)
        {


                if (m_BLL.Create(model))
                {
                    return Json(1, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(0, JsonRequestBehavior.AllowGet);
                }
     
        }
        #endregion

        #region 修改

        public ActionResult Edit(string id)
        {

            SysSampleModel entity = m_BLL.GetById(id);
            return View(entity);
        }

        [HttpPost]

        public JsonResult Edit(SysSampleModel model)
        {
           

                if (m_BLL.Edit(model))
                {
                    return Json(1, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(0, JsonRequestBehavior.AllowGet);
                }
           
        }
        #endregion

        #region 詳細
        public ActionResult Details(string id)
        {
            SysSampleModel entity = m_BLL.GetById(id);
            return View(entity);
        }

        #endregion

        #region 刪除
        [HttpPost]
        public JsonResult Delete(string id)
        {
            if (!string.IsNullOrWhiteSpace(id))
            {
                if (m_BLL.Delete(id))
                {
                    return Json(1, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    
                    return Json(0, JsonRequestBehavior.AllowGet);
                }
            }
            else
            {
                return Json(0, JsonRequestBehavior.AllowGet);
            }


        }
        #endregion
        
    }
}
SysSampleController

在創建視圖之前,我們先創建一個模板頁,打開views下面的Shared創建

<!DOCTYPE html>
<html>
<head>
    <title>Main</title>
    @Styles.Render("~/Content/themes/blue/css")
    <script src="@Url.Content("~/Scripts/jquery.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.form.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.easyui.min.js")" type="text/javascript"></script>
     <script src="@Url.Content("~/Scripts/jquery.easyui.plus.js")"></script>
    @Styles.Render("~/Content/css")
    <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>

</head>

<body>

        @RenderBody()

</body>
</html>
_Index_LayoutEdit.cshtml

我們以后的彈出窗口全部要用到這個模版,這個模版頁主要是引入了數據編輯和校驗
下面創建Create視圖

@model App.Models.Sys.SysSampleModel
@using App.Common;
@using App.Models.Sys;
@using App.Admin;
@{
     ViewBag.Title = "創建";
    Layout = "~/Views/Shared/_Index_LayoutEdit.cshtml";
    
}


<script type="text/javascript">
    $(function () {
        $("#btnSave").click(function () {
           
                $.ajax({
                    url: "/SysSample/Create",
                    type: "Post",
                    data: $("#CreateForm").serialize(),
                    dataType: "json",
                    success: function (data) {
                        if (data == 1) {
                            window.parent.frameReturnByMes("成功");
                            window.parent.frameReturnByReload(true);
                            window.parent.frameReturnByClose()
                        }
                        else {
                            window.parent.frameReturnByMes("失敗");
                        }
                    }
                });
        });
    });
    </script>


<div class="mvctool bgb">
    <a id="btnSave" style="float: left;" class="l-btn l-btn-plain"><span class="l-btn-left"><span class="l-btn-text icon-save" style="padding-left: 20px;">保存</span></span></a>
</div>
@using (Html.BeginForm("Create", "SysSample", null, FormMethod.Post, new { Id = "CreateForm" }))
{
    @Html.ValidationSummary(true)
    <table class="fromEditTable setTextWidth300">
        <tbody>
            <tr>
                <td style="width:100px; text-align:right;">
                    @Html.LabelFor(model => model.Id):
                </td>
                <td style="width:310px">
                    @Html.EditorFor(model => model.Id)
                </td>
                <td>@Html.ValidationMessageFor(model => model.Id)</td>
            </tr>
            <tr>
                <td style="width:100px; text-align:right;">
                    @Html.LabelFor(model => model.Name):
                </td>
                <td>
                    @Html.EditorFor(model => model.Name)
                </td>
                <td>
                    @Html.ValidationMessageFor(model => model.Name)
                </td>
            </tr>
            <tr>
                <td style="width:100px; text-align:right;">
                    @Html.LabelFor(model => model.Age):
                </td>
               
                <td>
                    @Html.EditorFor(model => model.Age)
                    </td>
                <td>
                    @Html.ValidationMessageFor(model => model.Age)
                </td>
            </tr>
            <tr>
                <td style="width:100px; text-align:right;">
                    @Html.LabelFor(model => model.Bir):
                </td>
                
                <td>
                    @Html.TextBoxFor(model => model.Bir)
                    </td>
                <td>
                    @Html.ValidationMessageFor(model => model.Bir)
                </td>
            </tr>
           
            <tr>
                <td style="width:100px; text-align:right;">
                    @Html.LabelFor(model => model.Note):
                </td>
               
                <td>
                    @Html.EditorFor(model => model.Note)
                    </td>
                <td>
                    @Html.ValidationMessageFor(model => model.Note)
                </td>
            </tr>
            <tr>
                <td style="width:100px; text-align:right;">
                    @Html.LabelFor(model => model.CreateTime):

                </td>
                
                <td>
                    @Html.TextBoxFor(model => model.CreateTime)
                   
                    </td>
                <td>
                    @Html.ValidationMessageFor(model => model.CreateTime)
                </td>
            </tr>
             <tr>
                <td style="width:100px; text-align:right;">
                    @Html.LabelFor(model => model.Photo):
                </td>
                  <td>
                      @Html.TextBoxFor(model => model.Photo)
               
                    </td>
               
                <td>
                    @Html.ValidationMessageFor(model => model.Photo)
                </td>
            </tr>
        </tbody>
    </table>
}
Create

總結

修改就把創建復制一份,保存的時候把url指到修改

詳細就把保存去掉就可以了

查詢,在Controller的GetList增加一個queryStr參數,在BLL判斷是queryStr是否為空。不為空就用Linq寫多個where,O了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM