JQuery dataTable 擴展+Ajax Post,Get一些基本操作(一)


首先, Asp.net MVC 系列暫時沒有發現封裝好的 類似於web form 的datagrid, 只有一款Jquery 的dataTable , 官網地址 http://www.datatables.net, 接下來講解一下關於自己在項目中對datatable進行擴展的一些實例。(first,Asp.net MVC have not packaging control similar the web form datagrid , and  now   i just konw Jquery dataTable, and The website address: http://www.datatables.net, the next ,i will list  some examples  that i have meet some issues in project),

直接上視圖代碼

<form method="post" onsubmit="return MaintainDel();">
    <div id="Message">
        <h3 style="color:red">@ViewBag.mes</h3>
    </div>
    <input id="ChooseUserId" name="ChooseUserId" type="hidden" />
    <div class="row">
        <div class="col-lg-12">
            <div class="panel panel-default">
                <!--<div class="panel-heading">
                    Users
                </div>-->

                <div class="panel-body">
                    <div class="table-responsive">
                        <table id="tab" class="table table-striped table-bordered table-hover">
                            <thead>
                                <tr>
                                    <th>Delete</th>
                                    <th>NRIC</th>
                                    <th>USER ID</th>
                                    <th>NAME</th>
                                    <th>Email</th>
                                    <th>ContactNo.</th>
                                    <th>Agency</th>
                                    <th>Designation</th>
                                    <th>SchemeRole</th>
                                    @*<th>IsDeleted</th>*@
                                </tr>
                            </thead>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="text-center">
        <input id="AddUserInfo" type="button" class="btn btn-default" value="Add User" onclick="AddUser();" name="btnaction" />&nbsp;
        <input id="DelUserInfo" type="submit" class="btn btn-default" value="Delete" name="btnaction" />
    </div>
    </form>

對於JQuerydatatable, 我們只需要在視圖中寫出table的head 就可以, 接下來是controller里面從數據庫拿一個list的方法,由於project用的是EF+MVC+Storeprocedure ,對於拿數據方面就不多講,下面是controller的代碼:

 [HttpGet]
        [MyAuthorize(ActionName = ActionCode.MaintainSuperUserAdmin)]
        public ActionResult MaintainSuperUserAdmin()
        {
            return View();
        }

        /// <summary>
        /// return Json Data for Jquery  Table
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        public JsonResult PageList(DataTablesParam parm)
        {
            int iDisplayStart = Convert.ToInt32(Request.Params["iDisplayStart"]);
            //data size
            int iDisplayLength = Convert.ToInt32(Request.Params["iDisplayLength"]);
            //data total            
            int totalCount;
            IEnumerable<UserUserInfo> user = this.ServiceLocator.GetService<IUserInfoRoleSchemeService>().GetUserInfoRoleSchemeViewInfo(Common.AdminRoleId.SuperAdminId, appid, iDisplayStart, iDisplayLength, out totalCount).ToList();
            return Json(new
            {
                sEcho = parm.sEcho,
                iTotalRecords = totalCount,
                iTotalDisplayRecords = totalCount,
                aaData = user
            }, JsonRequestBehavior.AllowGet);
        }

 一個Action對應一個View   改View的數據從Jsonresult中獲取。

[MyAuthorize(ActionName = ActionCode.MaintainSuperUserAdmin)]這段是用戶權限過濾器 就不細講,可用可不用。 主要代碼為
PageList中  拿list數據 以及返回Json格式。Dataparam為個人封裝的 可以接收JqueryDatatable 一些屬性的數據,(注意JQueryDatatable 自帶分頁效果)
public class DataTablesParam 
    {
        public int iDisplayStart { get; set; }
        public int iDisplayLength { get; set; }
        public int iColumns { get; set; }
        public string sSearch { get; set; }
        public bool bEscapeRegex { get; set; }
        public int iSortingCols { get; set; }
        public int sEcho { get; set; }
        public int total { get; set; }
        public List<bool> bSortable { get; set; }
        public List<bool> bSearchable { get; set; }
        public List<string> sSearchColumns { get; set; }
        public List<int> iSortCol { get; set; }
        public List<string> sSortDir { get; set; }
        public List<bool> bEscapeRegexColumns { get; set; }

        public DataTablesParam()
        {
            bSortable = new List<bool>();
            bSearchable = new List<bool>();
            sSearchColumns = new List<string>();
            iSortCol = new List<int>();
            sSortDir = new List<string>();
            bEscapeRegexColumns = new List<bool>();
        }

        public DataTablesParam(int iColumns)
        {
            this.iColumns = iColumns;
            bSortable = new List<bool>(iColumns);
            bSearchable = new List<bool>(iColumns);
            sSearchColumns = new List<string>(iColumns);
            iSortCol = new List<int>(iColumns);
            sSortDir = new List<string>(iColumns);
            bEscapeRegexColumns = new List<bool>(iColumns);
        }
    }

  Ok   一切就緒了,那么接下來就是如何將后台拿到的數據傳遞給View的Table,下面是關於這方面的JQuery代碼,關於datatable的一些屬性,大家就百度吧,,有用到的再說。

$(document).ready(function () {
        var admin = $('#tab').dataTable({
            "sAjaxSource": "@Url.Content("~/UserInfoRoleScheme/SchemePagelist")",
            //"sScrollX": "100%",
            "sScrollXInner": "100%",
            //"bScrollCollapse": true,
            "serverSide": true,
            'bPaginate': true,
            "bLengthChange": false,
            "bSort": false,
            "bFilter": false,
            "oLanguage": {
                "sZeroRecords": "@Messages.General.EmptyData.Format()",
                "sEmptyTable": "@Messages.General.EmptyData.Format()",
            },
            "aoColumnDefs": [
                  {
                      "render": function (data, type, full) {
                          if (full.IsDeleted == true) {
                              return full.UserName;
                          }
                          else {
                              return '<a href="' + "@Url.Content("~/UserInfoRoleScheme/UpdateSchemeUser")" + "?userid=" + full.UserId + '">' + full.FullName + '</a>';
                          }
                      },
                      "targets": 3
                  },
          {
              "render": function (data, type, full) {

                  return '<input type="checkbox" id="CheckUser" name="SelectedRoleId" class="userCheck" value="' + full.UserId + '"/>';
              },
              "targets": 0
          },
           {
               "render": function (data, type, full) {

                   return Trim(full.SchemeRole);
               },
               "targets": 8
           },
          //{
          //    "render": function (data, type, full) {
          //        if (full.IsDeleted == true) {
          //            return "Yes";
          //        }
          //        else {
          //            return "No";
          //        }
          //    },
          //    "targets": 10
          //},
            ],
            'aoColumns': [
                    { "mData": "UserInRoleId" },
                    { "mData": "Nric" },
                    { "mData": "AdId" },
                    { "mData": "FullName" },
                    { "mData": "EmailAddress" },
                    { "mData": "MobileAlias" },
                    { "mData": "AgencyId" },
                    { "mData": "Designation" },
                    { "mData": "SchemeRole" },
                    //{ "mData": "SchemeName" },
            ]
        });
    })

  該段JQuery代碼 ,,,注意

"mData"的時候 輸入的字段名字一定要與后台list的columns一致,不然獲取不到該列的數據,

"oLanguage": {
                "sZeroRecords": "@Messages.General.EmptyData.Format()",
                "sEmptyTable": "@Messages.General.EmptyData.Format()",
            },
改屬性為list為空的時候 JQueryTable顯示的errormessage ;

"aoColumnDefs": 是自己對datatable每一列的一些擴展定義,比如 當 我點擊每一行的名字的時候  鏈接到Update頁面更新該用戶的所有信息。
checkbox 每一行自動加上checkbox便於 進行一些操作,批量刪除,單個刪除等操作。
"targets"  從0 開始  可以定位到每一列 如 0  就是第一列 checkbox。

"render": function (data, type, full)   full為該行的所有數據,data 為該行該列的數據。

下面 為Jquery Datatable 的展示效果,很多屬性沒設置,,都是根據客戶需求來的,,各位可以參考官網自行設置。

加入了checkbox之后由於是根據后台的數據動態的顯示的,,所以checkbox的取值 給我了很大的困擾,下面的Jquery方法 是我感覺比較好的一種吧,一般的都是用id取值,但是在相同的id下 我們不得不考慮用id取值的准確性,因此,我們通過class 遍歷 對checkbox進行取值。
   
        var UserId="";
        $('.userCheck').each(function () {
            if (this.checked == true) {
                UserId += $(this).attr('value') + ','
            }            
        })    

  得到一個string類型的數據,就可以傳回后台通過一系列操作,達到自己想要操作的目的了。

自己整理的一些東西




免責聲明!

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



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