1. 程式人生 > 實用技巧 >layui 使用Mvc5+Dapper 動態渲染表格(table)元件 實現(查詢、新增、編輯、檢視、刪除)功能

layui 使用Mvc5+Dapper 動態渲染表格(table)元件 實現(查詢、新增、編輯、檢視、刪除)功能

目錄

前言

本章主要記錄,如何使用MVC5+Dapper動態渲染layui表格元件。就直接掠過如何建立mvc專案以及在專案中新增Dapper相關步驟。

如果對此有疑問的,請移步以下連結檢視相關操作。

.net Dapper 實踐系列(1) ---專案搭建(layui+mvc5+Dapper+MySQL)

一、實現table動態渲染以及查詢功能。

建立SJDA的控制器。建立列表檢視並引用layui.csslayui.js。宣告table元件。檢視完整程式碼如下所示:

<head>
    <meta name="viewport" content="width=device-width" />
    <title>司機檔案</title>
    <link href="~/Pulgs/layui/css/layui.css" rel="stylesheet" />
</head>
<body class="layui-bg-gray">
    <div class="layui-fluid">
        <div class="layui-card">
            <div class="layui-card-body">
                <div class="layui-row layui-form">
                    <div class="layui-col-lg12 layui-col-md12">
                        <div class="layui-form-label">篩選條件:</div>
                        <div class="layui-input-inline">
                            <select class="layui-select" id="selectKey">
                                <option value="">請輸入篩選條件</option>
                                <option value="xxx">身份證號</option>
                                <option value="xxx">司機名稱</option>
                            </select>
                        </div>
                        <div class="layui-input-inline">
                            <input type="text" name="mvalue" id="selectVale"  class="layui-input" placeholder="請輸入篩選內容" />
                        </div>
                        <button class="layui-btn " id="btnQuery"><i class="layui-icon">&#xe615;</i>查詢</button>
                        <button type="reset" class="layui-btn layui-btn-primary" id="btnClear">清空</button>
                    </div>
                </div>
                <hr class="layui-bg-green">
                <div class="layui-row">
                    <div class="layui-col-lg12">
                        <button class="layui-btn layui-btn-normal" id="btnAdd"><i class="layui-icon">&#xe608;</i>新增</button>
                    </div>
                </div>
                <div class="layui-row">
                    <div class="layui-col-lg12 layui-col-md12">
                        <table id="tab" lay-filter="tab"></table>
                        <script type="text/html" id="barOp">
                            <a class="layui-btn layui-btn-primary layui-btn-xs " lay-event="query">檢視</a>
                            <a class="layui-btn layui-btn-xs" lay-event="edit">編輯</a>
                            <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">刪除</a>
                        </script>
                        <script type="text/html" id="indexTpl">
                            {{d.LAY_TABLE_INDEX+1}}
                        </script>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!--引用jquery-->
    <script src="~/Content/js/jquery-1.12.4.min.js"></script>
    <!--引用layui-->
    <script src="~/Pulgs/layui/layui.js"></script>
    <!--引用 layer-->
    <script src="~/Pulgs/layer/2.4/layer.js"></script>
    <script type="text/javascript">
        layui.use(['table', 'layer', 'form', 'laydate'], function () {
            var table = layui.table, form = layui.form, layer = layui.layer;
            /*載入資訊*/
            table.render({
                elem: '#tab',
                url: '../xxx/xxx',
                cellMinWidth: 110,
                height: 'full-130',
                size: 'sm',
                cols: [[
                    //{ type: 'checkbox' },
                    { field: '', title: '', templet: '#indexTpl', align: 'center', width: '4%'  },
                    { field: 'xxx', title: '身份證號', sort: true, width: '15%'},
                    { field: 'xxx', title: '司機名稱', sort: true },
                    { field: 'xxx', title: '性別', sort: true },
                    { field: 'xxx', title: '家庭住址', sort: true },
                    { field: 'xxx', title: '車隊名稱', sort: true },
                    { field: 'xxx', title: '手機號碼', sort: true },
                    { field: 'xxx', title: '駕駛證有效期', sort: true, width: '15%' },
                    {
                        field: 'xxx', title: '是否有效', sort: true, templet: function (d) {
                            if (d.xxx== "True") {
                                return '有效';
                            } else {
                                return '禁用';
                            }
                        }
                    },
                    { fixed: 'right', title: '操作', toolbar: '#barOp', width: "16%" }
                ]],
                page: true,
                limit: 50,
            });
            /*查詢*/
            $("#btnQuery").click(function () {
                var mKey = $("#selectKey").val();
                var mValue = $("#selectVale").val();
                table.reload('tab', {
                    url: '../xxx/xxxx',
                    page: { curr: 1 },
                    where: {
                        mKey: mKey,
                        mValue: mValue,
                    }
                });
            });
            /*新增*/
            $("#btnAdd").click(function () {
                parent.layer.open({
                    type: 2,
                    title: '新增資訊',
                    amin: 4,
                    shadeClose: true,
                    shade: 0.8,
                    area: ['53%', '60%'],
                    content: '../xxx/xxx', //iframe的url
                    end: function () { $(".layui-laypage-btn").click();//重新繫結資料,防止刷新出現閃屏效果。 }
                });
            });
            /*檢視*/
            table.on('tool(tab)', function (obj) {
                var data = obj.data;
                var mId = obj.data.xxx;
                if (obj.event == 'query') {
                    parent.layer.open({
                        type: 2,
                        title: '檢視資訊',
                        amin: 4,
                        shadeClose: true,
                        shade: 0.8,
                        area: ['53%', '60%'],
                        content: '../xxx/xxx?Id=' + mId, //iframe的url
                        end: function () { }
                    });
                }
                /*編輯*/
                else if (obj.event == 'edit') {
                    parent.layer.open({
                        type: 2,
                        title: '編輯資訊',
                        amin: 4,
                        shadeClose: true,
                        shade: 0.8,
                        area: ['53%', '60%'],
                        content: '../xxx/xxx?Id=' + mId, //iframe的url
                        end: function () { $(".layui-laypage-btn").click();//重新繫結資料,防止刷新出現閃屏效果。 }
                    });
                }
                /*刪除*/
                else if (obj.event === 'del') {
                    layer.confirm('是否確定刪除?', function (index) {
                        $.ajax({
                            url: "../xxx/xxx?Id=" + mId,
                            type: "post",
                            async: false,
                        }).success(function (msg) {
                            if (msg > 0) {
                                layer.msg('刪除成功', { icon: 1 });
                                window.setTimeout(function () {
                                    $(".layui-laypage-btn").click();//重新繫結資料,防止刷新出現閃屏效果。
                                }, 1000);

                            } else {
                                layer.msg('刪除失敗', { icon: 2 });
                                window.setTimeout(function () {
                                    $(".layui-laypage-btn").click();//重新繫結資料,防止刷新出現閃屏效果。
                                }, 1000);
                            }
                        });
                    })
                }
            });
            /*清空*/
            $("#btnClear").click(function () {
                $("#selectKey").val("");
                $("#selectVale").val("");
                form.render();
            });
        });
    </script>
</body>

1.列表資料交換層控制器。

程式碼如下所示:

//需要宣告業務層例項
SjdaDal mdal = new SjdaDal();

#region 1.列表檢視
public ActionResult Sjda()
{
   return View();
}
#endregion

#region 2.列表請求
public string SjdaList(int page, int limit,string mKey,string mValue)
{
   string mWhere = "1=1";
   if (!string.IsNullOrEmpty(mKey) && !string.IsNullOrEmpty(mValue))
        mWhere += " and " + mKey + " like '%" + mValue + "%'";
   return mdal.SjdaList(page, limit, mWhere);
}
#endregion

2.業務處理層類。

程式碼如下所示:

#region 1.列表資訊顯示
/// <summary>
/// 1.列表資訊顯示
/// </summary>
/// <param name="page">當前頁碼數</param>
/// <param name="limit">每頁記錄條數</param>
/// <returns></returns>
public string SjdaList(int page, int limit, string mWhere)
{
    try
    {
       int total;
       string mJson = string.Empty;
       string mJsons = string.Empty;
       string mfiles = "";//查詢欄位
       string mtableName = "xxx";//表名或者檢視
       string mOrderBy = "xxx ";//排序欄位
       mfiles += " xxx,xxx";
       //獲取資料,並輸出總記錄數
       var result = DappvarerDBContext.GetPageList<xxx>(mfiles, mtableName, mWhere, mOrderBy, page, limit, out total).ToList();
       //格式化日期
       IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();
       timeFormat.DateTimeFormat = "yyyy-MM-dd ";
       //序列化資料
       mJson = JsonConvert.SerializeObject(result, Formatting.Indented, timeFormat);
       return mJsons = "{\"code\":0,\"msg\":\"\",\"count\":" + total + ",\"data\":" + mJson + "}";//拼接Json格式
     }
     catch (Exception)
     {
        throw;
     }
}
#endregion

3.資料訪問層處理類。

程式碼如下所示:

#region 通用分頁方法
// <summary>
/// 通用分頁方法
/// </summary>
/// <typeparam name="T">泛型集合實體類</typeparam>
/// <param name="files">列</param>
/// <param name="tableName">表</param>
/// <param name="where">條件</param>
/// <param name="orderby">排序</param>
/// <param name="pageIndex">當前頁</param>
/// <param name="pageSize">當前頁顯示條數</param>
/// <param name="total">結果集總數</param>
/// <returns></returns>
public static IEnumerable<T> GetPageList<T>(string files,string tableName,string where,string orderby,
int pageIndex,int pageSize,out int total)
{
    int skip = 1;
    if (pageIndex > 0)
    {
       skip = (pageIndex - 1) * pageSize + 1;
    }
    StringBuilder sb = new StringBuilder();
    sb.AppendFormat("SELECT COUNT(1) FROM {0} where {1};", tableName, where);
    sb.AppendFormat(@"SELECT  {0} FROM(SELECT ROW_NUMBER() OVER(ORDER BY {3}) AS RowNum,{0}  FROM {1} WHERE {2}) AS result 
    WHERE  RowNum >= {4}   AND RowNum <= {5} ORDER BY {3}", files, tableName, where, orderby, skip, pageIndex * pageSize);
    using (var conn = ConnectionFactory.SqlServerConn())
    {
        using (var reader = conn.QueryMultiple(sb.ToString()))
        {
             total = reader.ReadFirst<int>();
             return reader.Read<T>();
         }
    }
} 
#endregion

4.效果如下:

以上,即可實現動態渲染表格(table)元件並完成查詢功能。介面如下圖所示:

二、實現新增功能。

1.建立新增頁面檢視。

程式碼如下所示:

#region 1.新增檢視
public ActionResult SjdaAdd()
{
   return View();
}
#endregion

#region 2.新增操作
public int SjdaOpAdd(PE_MotorMan mJson)
{
    return mdal.SjdaOpAdd(mJson);
}
#endregion

2.新增檢視介面。

程式碼如下:

<head>
    <meta name="viewport" content="width=device-width" />
    <title>司機檔案-新增</title>
    <link href="~/Pulgs/layui/css/layui.css" rel="stylesheet" />
</head>
<body>
    <fieldset class="layui-elem-field" style="width:95%;margin:10px auto;">
        <div class="layui-field-box">
            <div class="layui-form layui-form-pane" lay-filter="bindData">
                <div class="layui-form-item">
                    <div class="layui-form-label"><span style="color:red;">*</span>身份證號碼</div>
                    <div class="layui-input-block">
                        <input type="text" name="xxx" lay-verify="required" placeholder="請輸入身份證號碼" class="layui-input" />
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-form-label"><span style="color:red;">*</span>有效期</div>
                    <div class="layui-input-inline">
                        <input type="text" name="xxx" lay-verify="required" placeholder="請輸入駕駛證有效期" class="layui-input"
                           id="dDate" />
                    </div>
                    <div class="layui-form-label"><span style="color:red;">*</span>司機名稱</div>
                    <div class="layui-input-inline">
                        <input type="text" name="xxx" lay-verify="required" placeholder="請輸入司機名稱"  class="layui-input" />
                    </div>
                </div>
                <div class="layui-form-item" pane>
                    <div class="layui-form-label">性別</div>
                    <div class="layui-input-block">
                        <input type="radio" name="xxx" value="男" title="男" checked="">
                        <input type="radio" name="xxx" value="女" title="女">
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-form-label">家庭地址</div>
                    <div class="layui-input-block">
                        <input type="text" name="xxx" placeholder="請輸入地址" autocomplete="off" class="layui-input" />
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-form-label">手機號碼</div>
                    <div class="layui-input-inline">
                        <input type="text" name="xxx" placeholder="請選擇手機號碼" autocomplete="off" class="layui-input" />
                    </div>
                    <div class="layui-form-label">車隊</div>
                    <div class="layui-input-inline">
                        <input type="text" name="xxx" placeholder="請輸入車隊" autocomplete="off" class="layui-input" />
                    </div>
                </div>
                <div class="layui-form-item" pane>
                    <div class="layui-form-label">是否有效</div>
                    <div class="layui-input-block">
                        <input type="radio" name="xxx" value="true" title="有效" checked="">
                        <input type="radio" name="xxx" value="false" title="無效">
                    </div>
                </div>
                <div class="layui-form-item">
                    <div style="text-align: center;">
                        <button class="layui-btn" lay-submit lay-filter="btnSave">儲存</button>
                        <button class="layui-btn layui-btn-primary" id="btnCancel">取消</button>
                    </div>
                </div>
            </div>
        </div>
    </fieldset>
    <!--引用jquery-->
    <script src="~/Content/js/jquery-1.12.4.min.js"></script>
    <!--引用layui-->
    <script src="~/Pulgs/layui/layui.js"></script>
    <script src="~/Moduls/myCommon.js"></script>
    <script type="text/javascript">
        var uName = "@(Session["uName"])";
        if (uName == "" || uName == null || uName == undefined) {
            jump("../Login/Login");
        }
        else {
            layui.use(['form', 'layer', 'laydate'], function () {
                var form = layui.form, layer = layui.layer, laydate = layui.laydate;
                form.render();
                laydate.render({ elem: "#dDate", type: "date"});
                /*儲存*/
                form.on('submit(btnSave)', function (data) {
                    $.ajax({
                        url: "../xxx/xxxx",
                        type: "post",
                        dataType: "json",
                        contentType: "application/json",
                        data: JSON.stringify(data.field)
                    }).done(function (msg) {
                        if (msg == 1) {
                            layer.msg("新增成功", { icon: 1 });
                            window.setTimeout(function () {
                                var index = parent.layer.getFrameIndex(window.name);
                                parent.layer.close(index);
                            }, 1000);
                        }
                        else if (msg == 2) { layer.msg("身份證號已存在,不可重複新增。", { icon: 7 }); return; }
                        else { layer.msg("新增失敗", { icon: 2 }); return; }
                    }).fail(function (e) { });
                    return false;
                });
                /*取消*/
                $("#btnCancel").click(function () {
                    var index = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(index);
                });
            });
        }
    </script>
</body>

3.實現新增方法。

程式碼如下:

#region 實現新增方法
/// <summary>
/// 實現新增方法
/// </summary>
/// <param name="mJson"></param>
/// <returns></returns>
public int SjdaOpAdd(xxxx mJson)
 {
      try
      {
         int mresult = 0;
         int mIsMomNO = IsMomNO(mJson.xxxx);//新增前判斷是否有同樣的身份證號 0無 1有
         if (mIsMomNO == 0)
         {
            xxx m = new xxx();//例項化物件
            m.xxx= mJson.xxx; //取值1
            m.xxx= mJson.xxx; //取值2
            
            //拼接sql語句
            string mSql = "insert into xxx";
            mSql += "(xxx,xxx) ";
            mSql += "values (@xxx,@xxx)";
            //執行新增操作
            int result=DapperDBContext.Execute(mSql, m);
            //返回結果集
            if (result > 0) { mresult = 1; }
          }
          else { mresult = 2; }
          
          return mresult;
    }
    catch (Exception)
    {
       throw;
    }
}
public int IsMomNO(string xxx)
{
   string mSql = "";
   int mResult = 0;
   DynamicParameters p = new DynamicParameters();
   mSql += "select count(xxx) from xxx where xxx=@ID";
   p.Add("@ID", xxx);
   var result = Convert.ToInt32(DapperDBContext.ExecuteScalar(mSql, p));
   if (result > 0) { mResult = 1; }
   return mResult;
}
#endregion

4.效果如下:

三、實現檢視功能

1.建立檢視檢視頁面

程式碼如下所示:

#region 檢視檢視
public ActionResult SjdaLook(string Id)
{
    ViewBag.Id = Id;
    return View();
}
#endregion

2.檢視頁面檢視。

程式碼如下所示:

<head>
    <meta name="viewport" content="width=device-width" />
    <title>司機檔案-檢視</title>
    <link href="~/Pulgs/layui/css/layui.css" rel="stylesheet" />
</head>
<body>
    <fieldset class="layui-elem-field" style="width:95%;margin:10px auto;">
        <div class="layui-field-box">
            <div class="layui-form layui-form-pane" lay-filter="bindData">
                <div class="layui-form-item">
                    <div class="layui-form-label"><span style="color:red;">*</span>身份證號碼</div>
                    <div class="layui-input-block">
                        <input type="text" name="xxx" lay-verify="required" placeholder="請輸入身份證號碼" class="layui-input" />
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-form-label"><span style="color:red;">*</span>駕駛證有效期</div>
                    <div class="layui-input-inline">
                        <input type="text" name="xxx" lay-verify="required" placeholder="請輸入駕駛證有效期"  class="layui-input"
                         id="dDate" />
                    </div>
                    <div class="layui-form-label"><span style="color:red;">*</span>司機名稱</div>
                    <div class="layui-input-inline">
                        <input type="text" name="xxx" lay-verify="required" placeholder="請輸入司機名稱"  class="layui-input" />
                    </div>
                </div>
                <div class="layui-form-item" pane>
                    <div class="layui-form-label">性別</div>
                    <div class="layui-input-block">
                        <input type="radio" name="xxx" value="男" title="男" checked="">
                        <input type="radio" name="xxx" value="女" title="女">
                    </div>
                </div>
                <div class="layui-form-item" style="width:80%;">
                    <div class="layui-form-label">家庭地址</div>
                    <div class="layui-input-block" style="width: 100%;">
                        <input type="text" name="xx" placeholder="請輸入家庭地址" autocomplete="off" class="layui-input"  />
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-form-label">手機號碼</div>
                    <div class="layui-input-inline">
                        <input type="text" name="xxx" placeholder="請選擇手機號碼" autocomplete="off" class="layui-input" />
                    </div>
                    <div class="layui-form-label">車隊</div>
                    <div class="layui-input-inline">
                        <input type="text" name="xxx" placeholder="請輸入車隊" autocomplete="off" class="layui-input" />
                    </div>
                </div>
                <div class="layui-form-item" pane>
                    <div class="layui-form-label">是否有效</div>
                    <div class="layui-input-block">
                        <input type="radio" name="xxx" value="true" title="有效" checked="">
                        <input type="radio" name="xxx" value="false" title="無效">
                    </div>
                </div>
                <div class="layui-form-item">
                    <div style="text-align: center;">
                        <button class="layui-btn layui-btn-primary" id="btnCancel">取消</button>
                    </div>
                </div>
            </div>
        </div>
    </fieldset>
    <!--引用jquery-->
    <script src="~/Content/js/jquery-1.12.4.min.js"></script>
    <!--引用layui-->
    <script src="~/Pulgs/layui/layui.js"></script>
    <script src="~/Moduls/myCommon.js"></script>
    <script type="text/javascript">
        var uName = "@(Session["uName"])";
        var Id = "@ViewBag.Id";
        if (uName == "" || uName == null || uName == undefined) {
            jump("../Login/Login");
        }
        else {
            layui.use(['form', 'layer', 'laydate'], function () {
                var form = layui.form, layer = layui.layer, laydate = layui.laydate;
                form.render();
                laydate.render({ elem: "#dDate", type: "date", value: new Date() });
                /*查詢*/
                $.get("../xxx/xxx?ID=" + Id, function (msg) {
                    var mJSON = $.parseJSON(msg);
                    if (msg != "") {
                        form.val('bindData', {
                            "xxx": mJSON.xxx,
                            "xxx": mJSON.xxx,
                            "xxx": mJSON.xxx,
                            "xxx": mJSON.xxx,
                            "xxx": mJSON.xxx,
                            "xxx": mJSON.xxx,
                            "xxx": mJSON.xxx,
                            "xxx": mJSON.xxx,
                            "xxx": "" + mJSON.xxx+ ""
                        });
                    }
                });
                /*取消*/
                $("#btnCancel").click(function () {
                    var index = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(index);
                });
            });
        }
    </script>
</body>

3.檢視檢視實現。

程式碼如下所示:

#region 根據ID查詢
/// <summary>
/// 根據ID查詢
/// </summary>
/// <returns></returns>
public string SjdaLookById(string Id)
{
   try
   {
       DynamicParameters p = new DynamicParameters();
       string msql = "select * from xxx where xxx=@Id";
       p.Add("@Id", Id);
       IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();
       timeFormat.DateTimeFormat = "yyyy-MM-dd";
       var result = DapperDBContext.Query<xxx>(msql, p).FirstOrDefault();
       return JsonConvert.SerializeObject(result, Formatting.Indented, timeFormat);
     }
     catch (Exception)
     {
        throw;
     }
 }
#endregion

4.效果如下圖所示:

四、實現編輯功能

1.建立編輯檢視頁面

程式碼如下所示:

#region 編輯檢視
public ActionResult SjdaEdit(string Id)
{
    ViewBag.Id = Id;
    return View();
}
#endregion

#region 編輯操作
public int SjdaOpEdit(xxx mJson)
{
   return mdal.SjdaOpEdit(mJson);
}
#endregion

2.編輯頁面檢視。

程式碼如下所示:

<head>
    <meta name="viewport" content="width=device-width" />
    <title>司機檔案-檢視</title>
    <link href="~/Pulgs/layui/css/layui.css" rel="stylesheet" />
</head>
<body>
    <fieldset class="layui-elem-field" style="width:95%;margin:10px auto;">
        <div class="layui-field-box">
            <div class="layui-form layui-form-pane" lay-filter="bindData">
                <div class="layui-form-item">
                    <div class="layui-form-label"><span style="color:red;">*</span>身份證號碼</div>
                    <div class="layui-input-block">
                        <input type="text" name="xxx" lay-verify="required" placeholder="請輸入身份證號碼" autocomplete="off" 
                         class="layui-input" disabled="disabled" />
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-form-label"><span style="color:red;">*</span>駕駛證有效期</div>
                    <div class="layui-input-inline">
                        <input type="text" name="xxx" lay-verify="required" placeholder="請輸入駕駛證有效期" autocomplete="off" 
                        class="layui-input" id="dDate" />
                    </div>
                    <div class="layui-form-label"><span style="color:red;">*</span>司機名稱</div>
                    <div class="layui-input-inline">
                        <input type="text" name="xxxx" lay-verify="required" placeholder="請輸入司機名稱" autocomplete="off" 
                        class="layui-input" />
                    </div>
                </div>
                <div class="layui-form-item" pane>
                    <div class="layui-form-label">性別</div>
                    <div class="layui-input-block">
                        <input type="radio" name="xxx" value="男" title="男" checked>
                        <input type="radio" name="xxxx" value="女" title="女">
                    </div>
                </div>
                <div class="layui-form-item" style="width:80%;">
                    <div class="layui-form-label">家庭地址</div>
                    <div class="layui-input-block" style="width: 100%;">
                        <input type="text" name="xxx" placeholder="請輸入家庭地址" autocomplete="off" class="layui-input" />
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-form-label">手機號碼</div>
                    <div class="layui-input-inline">
                        <input type="text" name="xxx" placeholder="請選擇手機號碼" autocomplete="off" class="layui-input" />
                    </div>
                    <div class="layui-form-label">車隊</div>
                    <div class="layui-input-inline">
                        <input type="text" name="xxx" placeholder="請輸入車隊" autocomplete="off" class="layui-input" />
                    </div>
                </div>
                <div class="layui-form-item" pane>
                    <div class="layui-form-label">是否有效</div>
                    <div class="layui-input-block">
                        <input type="radio" name="xxx" value="true" title="有效" checked>
                        <input type="radio" name="xxx" value="false" title="無效">
                    </div>
                </div>
                <div class="layui-form-item">
                    <div style="text-align: center;">
                        <button class="layui-btn" lay-submit lay-filter="btnSave">儲存</button>
                        <button class="layui-btn layui-btn-primary" id="btnCancel">取消</button>
                    </div>
                </div>
            </div>
        </div>
    </fieldset>
    <!--引用jquery-->
    <script src="~/Content/js/jquery-1.12.4.min.js"></script>
    <!--引用layui-->
    <script src="~/Pulgs/layui/layui.js"></script>
    <script src="~/Moduls/myCommon.js"></script>
    <script type="text/javascript">
        var uName = "@(Session["uName"])";
        var Id = "@ViewBag.Id";
        if (uName == "" || uName == null || uName == undefined) {
            jump("../Login/Login");
        }
        else {
            layui.use(['form', 'layer', 'laydate'], function () {
                var form = layui.form, layer = layui.layer, laydate = layui.laydate;
                form.render();
                laydate.render({ elem: "#dDate", type: "date", value: new Date() });
                /*查詢*/
                $.get("../Sjda/SjdaLookById?ID=" + Id, function (msg) {
                    var mJSON = $.parseJSON(msg);
                    if (msg != "") {
                        form.val('bindData', {
                            "xxx": mJSON.xxx,
                            "xxx": mJSON.xxx,
                            "xxx": mJSON.xxx,
                            "xxx": mJSON.xxx,
                            "xxx": mJSON.xxx,
                            "xxx": mJSON.xxx,
                            "xxx": mJSON.xxx,
                            "xxx": mJSON.xxx,
                            "xxx": "" + mJSON.xxx+ ""
                        });
                    }
                });
                /*儲存*/
                form.on('submit(btnSave)', function (data) {
                    $.ajax({
                        url: "../Sjda/SjdaOpEdit",
                        type: "post",
                        dataType: "json",
                        contentType: "application/json",
                        data: JSON.stringify(data.field)
                    }).done(function (msg) {
                        if (msg == 1) {
                            layer.msg("編輯成功", { icon: 1 });
                            window.setTimeout(function () {
                                var index = parent.layer.getFrameIndex(window.name);
                                parent.layer.close(index);
                            }, 1000);
                        }
                        else { layer.msg("編輯失敗", { icon: 2 }); return; }
                    }).fail(function (e) { });
                    return false;
                });
                /*取消*/
                $("#btnCancel").click(function () {
                    var index = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(index);
                });
            });
        }
    </script>
</body>

3.編輯功能實現。

程式碼如下所示:

#region 編輯
/// <summary>
/// 編輯
/// </summary>
/// <param name="mJson"></param>
/// <returns></returns>
public int SjdaOpEdit(xxx mJson)
{
   try
   {
      xxx m = new xxx();
      m.xx= mJson.xxx;
      m.xx= mJson.xxx;
      m.xx= mJson.xxx;


      string mSql = "update xxx set xx=@xxx,xx=@xxx,xx=@xxx";
      mSql += " where xx=@xxx";
      int result = DapperDBContext.Execute(mSql, m);
      return result;
    }
    catch (Exception)
    {
       throw;
    }
}
#endregion


4.效果如下圖所示:

五、實現刪除功能

1.實現刪除功能。

在控制器中程式碼如下所示:

#region 5.刪除
public int SjdaOpDel(string Id)
{
   return mdal.SjdaOpDel(Id);
}
#endregion

業務層程式碼如下所示:

#region 刪除
/// <summary>
/// 刪除
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
public int SjdaOpDel(string id)
{
   try
   {
      DynamicParameters p = new DynamicParameters();
      string mSql = "delete from xxx where xxx=@Id";
      p.Add("@Id", id);
      return DapperDBContext.Execute(mSql, p);
    }
    catch (Exception)
    {
       throw;
    }
}
#endregion

2.效果如下所示:


六、總結

至此,基本實現了資料基本的操作。如有不明白之處或者有更好的實現方式,歡迎大家指出。有則改之無則加勉。

你知道的越多,你不知道的閱讀。我們不生產知識,我們只是知識的搬運工。