首页 > 代码库 > MVC JQuery Table Ajax 的一些扩展和应用

MVC JQuery Table Ajax 的一些扩展和应用

  1 ///Home page   2 public ActionResult MaintainSuperUserAdmin()  3         {                          4             return View();  5         }  6   7         /// <summary>  8         /// return Json Data for Jquery  Table  9         /// </summary> 10         /// <param name="parm"></param> 11         /// <returns></returns> 12         public JsonResult PageList(DataTablesParam parm) 13         { 14             int iDisplayStart = Convert.ToInt32(Request.Params["iDisplayStart"]); 15             //data size 16             int iDisplayLength = Convert.ToInt32(Request.Params["iDisplayLength"]); 17             //data total             18             int totalCount = 0; 19             IEnumerable<UserProfileRoleSchemeView> user = db.P_V_USER_PROFILE_ROLE_SCHEME_S_BY_APPID_ROLEID(appid, Sid).ToList(); 20             totalCount = user.OrderBy(m=>m.LAST_ACTIVITY_TIME).ToList().Count(); 21  22             user = user.Skip(iDisplayStart).Take(iDisplayLength).ToList(); 23  24             return Json(new 25             { 26                 sEcho = parm.sEcho, 27                 iTotalRecords = totalCount, 28                 iTotalDisplayRecords = totalCount, 29                 aaData =http://www.mamicode.com/ user 30             }, JsonRequestBehavior.AllowGet); 31         } 32  33 ///add Ajax Post 34  [HttpPost] 35         public JsonResult Add(string SchemeId, string RoleId) 36         { 37             bool result=false; 38             List<RoleScheme> admin = (List<RoleScheme>)Session["RoleScheme"];            39             RoleScheme rs = new RoleScheme();             40             //rs.SchemeId = Convert.ToInt32(Request["SchemeId"]); 41             //rs.RoleId = Request["RoleId"];             42             rs.SchemeId =Convert.ToInt32(SchemeId); 43             rs.RoleId = RoleId;              44             var role = cUser.Roles.Where(m => m.ROLE_ID == rs.RoleId).FirstOrDefault(); 45             rs.RoleName = role.ROLE_NAME; 46             var Scheme = db.Schemes.Where(m => m.SCHEME_ID == rs.SchemeId).FirstOrDefault(); 47             rs.SchemeName = Scheme.SCHEME_NAME; 48             foreach (var model in admin) 49             { 50                 if (model.RoleId == rs.RoleId & model.SchemeId == rs.SchemeId) 51                     result = true; 52             } 53             if (result) 54             { 55                 return Json("No", JsonRequestBehavior.AllowGet); 56             } 57             else 58             { 59                 admin.Add(rs); 60                 Session["RoleScheme"] = admin; 61                 return Json("OK", JsonRequestBehavior.AllowGet); 62             } 63         } 64 //Delete Ajax Post 65         [HttpPost] 66         public JsonResult Delete(string SchemeIdAndRoleId) 67         { 68             int SchemeId; 69             string RoleId = ""; 70             SchemeIdAndRoleId = SchemeIdAndRoleId.Remove(SchemeIdAndRoleId.Length - 1); 71             var list = SchemeIdAndRoleId.Split(,).ToList(); 72             List<RoleScheme> admin = (List<RoleScheme>)Session["RoleScheme"]; 73             if (list.Count > 1) 74             {                75                 for (int i = 0; i < list.Count; i++) 76                 { 77                     RoleId = list[i].Split(&)[0].ToString(); 78                     SchemeId = Convert.ToInt32(list[i].Split(&)[1].ToString()); 79                     RoleScheme roleAndS = admin.Where(m => m.RoleId == RoleId & m.SchemeId == SchemeId).FirstOrDefault(); 80                     admin.Remove(roleAndS); 81                 } 82                 Session["RoleScheme"] = admin; 83                 return Json("OK", JsonRequestBehavior.AllowGet); 84             } 85             else 86             { 87                 RoleId = SchemeIdAndRoleId.Split(&)[0].ToString(); 88                 SchemeId = Convert.ToInt32(SchemeIdAndRoleId.Split(&)[1].ToString()); 89                 RoleScheme roleAndS = admin.Where(m => m.RoleId == RoleId & m.SchemeId == SchemeId).FirstOrDefault(); 90                 admin.Remove(roleAndS); 91                 Session["RoleScheme"] = admin; 92                 return Json("OK", JsonRequestBehavior.AllowGet); 93             }             94         } 95  96         public JsonResult Get() 97         { 98             RoleScheme rsIndex = new RoleScheme();            99             rsIndex.SchemeName ="Sample(GST)";100             rsIndex.RoleName = "Sample(SUPERUSER)";101             if (Session["RoleScheme"] == null)102             {103                 List<RoleScheme> users = new List<RoleScheme>();104                 users.Add(rsIndex);105 106                 Session["RoleScheme"] = users;107             }            108             Dictionary<string, List<RoleScheme>> result = new Dictionary<string, List<RoleScheme>>();109             result["aaData"] = (List<RoleScheme>)Session["RoleScheme"];          110             return Json(result, JsonRequestBehavior.AllowGet);111         }
Controller


Model为自定义的, 该项目为MVC DataBaseFirst   数据源是一个多个表组成的view。

 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using CPFB.AWP.GPP.Models; 6 using System.ComponentModel.DataAnnotations; 7 using CPFB.AWP.Common.Models; 8 using System.Web.Mvc; 9 10 namespace CPFB.AWP.GPP.Web.Admin.Mvc.Models11 {12     public class MaintainUserAdminModel13     {14         15     }16     public class UserAdmin17     {18         [Required]        19         public int USERS_IN_ROLES_ID { get; set; }20         [Required]21         public string USER_ID { get; set; }22         [Required]23         public string ADID { get; set; }24         [Required(ErrorMessage="Pls Input a Value")]25         public string NAME { get; set; }26         [Required]27         public string NRIC { get; set; }28         [Required]29         public string Email { get; set; }30         [Required]31         public string ContractNumber { get; set; }32        33         [Required(ErrorMessage="Not Null")]34         public string AgencyId { get; set; }35         [Required]36         public string Designation { get; set; }37        38         [Required(ErrorMessage="Not Null")]        39         public int SchemeId { get; set; }40 41         [Required(ErrorMessage = "Not Null")]   42         public string RoleId { get; set; }43         [Required]44         public bool IsVip { get; set; }45         [Required]46         public bool IsDelete { get; set; }47         [Required]48         public bool IsPostQA { get; set; }49         [Required]50         public int VERSIONNO { get; set; }51         [Required]52         public string TRANSACTIONID { get; set; }53         [Required]54         public string CREATEBY { get; set; }55         [Required]56         public DateTime CREATETIME { get; set; }       57     }58     public class RoleScheme59     {        60         public int SchemeId { get; set; }61         public string RoleId { get; set; }62         public string SchemeName { get; set; }63         public string RoleName { get; set; }64     }65 }
Model

 关于Jquery  Table  还是需要多查询一些属性。
View 中由于一些需求更改,,注释了许多东西,注释的也是可以完成的一些基本功能

  1 <div><h4>MaintainSuperUserAdmin</h4>  2     <h5 style="color:red">@ViewBag.mes</h5>  3     </div>  4 @using (Html.BeginForm(new { id = "Grid-form", @role = "form", @class = "form-horizontal" }))  5 {  6     <table id="tab">  7         <thead>  8             <tr>  9                 <th>Delete</th>                 10                 <th>Scheme</th> 11                 <th>NAME</th> 12                 <th>Email</th> 13                 <th>Contract Number</th> 14                 <th>Agency</th> 15                 <th>Designation</th> 16                 <th>Scheme</th> 17                 <th>IsDeleted</th>              18             </tr> 19         </thead> 20     </table> 21     <div class="text-center"> 22         <input id="AddUserInfo" type="submit" value=http://www.mamicode.com/"Add User" name="btnaction" /> 23         <input id="DelUserInfo" type="submit" value=http://www.mamicode.com/"Delete" name="btnaction" /> 24     </div> 25 } 26  27  28  29 @section Scripts{ 30     <script type="text/javascript"> 31         var url = "";         32         $(document).ready(function () { 33             var admin = $(#tab).dataTable({ 34                 "sScrollX": "100%",                35                 "sScrollXInner": "100%", 36                 "bScrollCollapse": true, 37                 "processing": true, 38                 "serverSide": true, 39                 bPaginate: true, 40                 "sAjaxSource": "/UserProfileRoleSchemeViews/PageList", 41                 iDisplayLength: 8, 42                 "bLengthChange": false, 43                 "bFilter": false,                 44                 "aoColumnDefs": [                    45                       { 46                           "render": function (data, type, full) { 47                               if (full.IS_DELETED == true) { 48                                   return full.USER_NAME; 49                               } 50                               else { 51                                   return <a href="http://www.mamicode.com/UserProfileRoleSchemeViews/UpdateSuperUser + "?userid=" + full.USER_ID + "&roleid=" + full.ROLE_ID + 52                                       "&SchemeId=" + full.SCHEME_ID + "> + full.USER_NAME + </a>; 53                               } 54                           }, 55                           "targets": 2 56                       },                      57                       { 58                           "render": function (data, type, full) { 59                               if (full.IS_DELETED == true) { 60                                   return <input type="checkbox" id="CheckUser" name="SelectedRoleId" value="http://www.mamicode.com/ + full.IS_DELETED + "/>; 61                               } 62                               else { 63                                   return <input type="checkbox" id="CheckUser" name="SelectedRoleId" value="http://www.mamicode.com/ + full.USER_ID + & + full.USERS_IN_ROLES_ID + & + full.IS_DELETED + "/>; 64                               } 65                           }, 66                           "targets": 0 67                       }, 68                       //{ 69                       //    "render": function (data, type, full) { 70                       //        return ‘<input id="btnAdd" type="button" onclick="keleyidialog(‘ + full.USERS_IN_ROLES_ID + ‘);" value="http://www.mamicode.com/AddRole"/>‘; 71                       //    }, 72                       //    "targets": 9 73                       //}, 74                       { 75                           "render": function (data, type, full) { 76                               if (full.IS_DELETED == true) { 77                                   return "Yes"; 78                               } 79                               else { 80                                   return "No"; 81                               } 82                           }, 83                           "targets": 8 84                       },                85                 ], 86                 aoColumns: [ 87                         { "mData": "USERS_IN_ROLES_ID" },                         88                         { "mData": "AD_ID" }, 89                         { "mData": "USER_NAME" }, 90                         { "mData": "EMAIL_ADDRESS" }, 91                         { "mData": "MOBILE_ALIAS" }, 92                         { "mData": "AGENCY_ID" }, 93                         { "mData": "DESIGNATION" }, 94                         { "mData": "SCHEME_NAME" }, 95                         {"mData":"IS_DELETED"}, 96                         //{ "mData": null },                        97                 ] 98             }); 99             //$("#tab tbody").on(‘click‘, ‘button‘, function  Clic(){100             //    var clickfull=$(this).parents("tr")[0].sectionRowIndex;101             //    var data = http://www.mamicode.com/$("#tab tbody tr")[clickRow].parentNode.children[clickRow].innerHTML;102             //})103             //var formOptions = {104             //    success: function (responseText, statusText, xhr, $form) {105 106             //        if (responseText == "OK") {107 108             //            admin.ajax.reload();109             //        }110             //    },111             //    dataType: "json"112             //};113             //$("#add-form").ajaxForm(formOptions);114             //$("#AddRole").click(function () {115             //    var oSettings = admin.fnSettings();116             //    oSettings.sAjaxSource = "/UserProfileRoleSchemeViews/PageList";117             //    alert(oSettings.sAjaxSource);118             //    admin.fnClearTable(0);119             //    admin.fnDraw();120             //});121         })122 123 124         //var row = $(‘#dg‘).datagrid(‘getSelected‘);125         //if (row) {126         //    $(‘#dlg‘).dialog(‘open‘).dialog(‘setTitle‘, ‘Edit User‘);127         //    $(‘#fm‘).form(‘load‘, row);128         //    url = ‘update_user.php?id=‘ + row.id;129         //}130 131 132         //function keleyidialog(userinroleid) {133         //    $("#table").dialog(134         //        {135         //            title: "Add Role And Scheme",136         //            resizable: false,137         //            height: 240,138         //            width: 400,139         //            modal: true,140         //        }141         //        );142         //    document.getElementById(‘USERS_IN_ROLES_ID‘).value = http://www.mamicode.com/userinroleid;            >143         //}144 145         146         //function getDate()147         //{148         //    var result;149         //    jQuery.ajax({150         //        type: ‘POST‘,151         //        async: false,152         //        url: ‘../hand/UserDel.ashx?uid=‘ + depCodeVal + ‘‘,153         //        data: ‘‘,154         //        success: function (data) {155         //            if (data.length > 0) {156         //                result = data;157         //            }158         //        }159         //    });160         //}161         //function hidden()162         //{163         //    $("#table").hide();164         //}165 166     </script>167 }
View
  1 <h2>AddSuperUser</h2>  2   3   4 @using (Html.BeginForm())  5 {  6     @Html.AntiForgeryToken()  7     <div class="row">  8         <table class="table table-striped table-bordered table-hover" id="dataTables-example">  9             <tr> 10                 <td></td> 11             </tr> 12             <tr> 13                 <td> 14                     USER ID 15                 </td> 16                 <td> 17                     @Html.TextBoxFor(model => model.ADID) 18                     @Html.ValidationMessageFor(model => model.ADID) 19                 </td> 20             </tr> 21             <tr> 22                 <td> 23                     NAME 24                 </td> 25                 <td> 26                     @Html.TextBoxFor(model => model.NAME) 27                     @Html.ValidationMessageFor(model => model.NAME) 28                 </td> 29             </tr> 30             <tr> 31                 <td> 32                     Email 33                 </td> 34                 <td> 35                     @Html.TextBoxFor(model => model.Email) 36                 </td> 37             </tr> 38             <tr> 39                 <td> 40                     Contract Number 41                 </td> 42                 <td> 43                     @Html.TextBoxFor(model => model.ContractNumber) 44                 </td> 45             </tr> 46             <tr> 47                 <td> 48                     Agency 49                 </td> 50                 <td> 51                     @*@Html.DropDownListFor(model => model.Schemalist, @ViewData["Schemalist"] as SelectList)*@ 52                     @Html.DropDownListFor(model=>model.AgencyId,(SelectList)ViewData[Constants.AdminMoudle.Agencylist], Constants.AdminMoudle.ListIndex) 53                     @Html.ValidationMessageFor(model => model.AgencyId) 54                 </td> 55             </tr> 56             <tr> 57                 <td> 58                     Designation 59                 </td> 60                 <td> 61                     @Html.TextBoxFor(model => model.Designation) 62                     @Html.ValidationMessageFor(model => model.Designation) 63                 </td> 64             </tr> 65         </table> 66     </div> 67     <div class="row"> 68         <div>Access Rights</div>  69         <table class="table table-striped table-bordered table-hover" id="AccessRights"> 70             <thead> 71                 <tr>  72                     <th>Delete</th>                  73                     <th>Schema</th> 74                     <th>Role</th> 75                 </tr> 76             </thead>                     77         </table>     78         <div> 79             <input id="AddAccess" type="button" value=http://www.mamicode.com/"Add" onclick="keleyidialog();"  name="action" /> 80             <input id="DelAccess" type="button" value=http://www.mamicode.com/"Delete"  name="action" onclick="Del();"/> 81         </div> 82     </div> 83     <div class="text-center"> 84         <input id="AddUser" type="submit" value=http://www.mamicode.com/"Add User" name="action" /> 85         <input id="btnClear" type="button" value=http://www.mamicode.com/"Cancel" onclick="formReset();" name="action" />         86     </div>         87 } 88  89 <div id="table" style="display:none"> 90     @using (Html.BeginForm("../UserProfileRoleSchemeViews/Add", "Add", FormMethod.Post, new { id = "add-form", @role = "form" })) 91     { 92          93         @Html.HiddenFor(model => model.USERS_IN_ROLES_ID) 94         @Html.HiddenFor(model => model.USER_ID)        95         <table id="example" class="table table-striped table-bordered table-hover"> 96              97             <tr> 98                 <td>Scheme</td> 99                 <td>100                     @Html.DropDownListFor(model => model.SchemeId, (SelectList)ViewData[Constants.AdminMoudle.Schemalist], Constants.AdminMoudle.ListIndex)101                     @Html.ValidationMessageFor(model => model.SchemeId)102                 </td>103             </tr>104             <tr>105                 <td>Role</td>106                 <td>                    107                     @Html.DropDownListFor(model => model.RoleId, (SelectList)ViewData[Constants.AdminMoudle.Rolelist])108                     @Html.ValidationMessageFor(model => model.RoleId)109                 </td>110             </tr>111         </table>112         <div class="text-center">113             <input id="AddRole" type="submit" value=http://www.mamicode.com/"Add"  name="btnaction" />114         </div>115     }116 </div>117 <script type="text/javascript">118 function formReset()119 {120     $("#ADID").val("");121     $("#NAME").val("");122     $("#Email").val("");123     $("#ContractNumber").val("");124     $("#Agencylist").val("");125     $("#Designation").val("");126     $("#Schemalist").val("");   127 }128 129 </script>130 131 @section Scripts {132 <script type="text/javascript">133 134     $(document).ready(function () {135 136         var adminGrid = $("#AccessRights").DataTable({137             "sAjaxSource": "/UserProfileRoleSchemeViews/Get",138             "sScrollX": "100%",139             "sScrollXInner": "100%",140             "bScrollCollapse": true,            141             "aoColumnDefs": [142                 {143                     "render": function (data, type, full) {                        144                         return <input type="checkbox" id="CheckRole" name="CheckSelect" value="http://www.mamicode.com/ + full.RoleId + & + full.SchemeId + "/>;145                     },146                     "targets": 0147                 },148             ],149             "aoColumns": [150                     { "mData": null },151                     { "mData": "SchemeName" },152                     { "mData": "RoleName" }],153         });        154         var formOptions = {155             success: function (responseText, statusText, xhr, $form) {156 157                 if (responseText == "OK") {158                     adminGrid.ajax.reload();159                 }160             },           161             dataType: "json"162         };163 164         $("#add-form").ajaxForm(formOptions);              165     });166 167     function keleyidialog() {168         $(#SchemeId).val("");169         $("#table").dialog(170             {171                 title: "Add Role And Scheme",172                 resizable: false,173                 height: 240,174                 width: 400,175                 modal: true,                176             }177             );     178     }179    180 181     function Del() {182         //var SchemeIdAndRoleId = $(‘input:checkbox:checked‘).val();183         //var s = $(‘input:checkbox:checked‘).val();184         //alert(s);               185         var SchemeIdAndRoleId = "";186         $("[name=‘CheckSelect‘]:checked").each(function (index, element) {187 188             SchemeIdAndRoleId += $("[name=‘CheckSelect‘]:checked").val() + ",";189 190         });        191         if (SchemeIdAndRoleId == "") {192             alert("Pls Choose one or more to Delete");193         }194         else if (SchemeIdAndRoleId == "null&0,")195         {196             alert("The Sample Records not allow delete");197             $("#AccessRights").DataTable().ajax.reload();198         }199         else {200             $.ajax({201                 type: POST,202                 url: "/UserProfileRoleSchemeViews/Delete",203                 dataType: "json",204                 data: { SchemeIdAndRoleId: SchemeIdAndRoleId },205                 success: function (responseText, statusText, xhr, $form) {206 207                     if (responseText == "OK") {208                         $("#AccessRights").DataTable().ajax.reload();209                     }                   210                 },211                 dataType: "json"212             });213         }214     }215 216     $("#AddRole").click(217         function () {            218             $(#table).dialog(close);219             var SchemeId = $(#SchemeId).val();220             var RoleId = $(#RoleId).val();221             $.ajax({222                 type: POST,223                 url: "/UserProfileRoleSchemeViews/Add",224                 dataType: "json",225                 data: {226                     SchemeId: SchemeId,227                     RoleId:RoleId228                 },229                 success: function (responseText, statusText, xhr, $form) {230 231                     if (responseText == "No") {232                         alert("The records have Exist,Please do not add a duplicate");233                         $("#AccessRights").DataTable().ajax.reload();234                     }235                     else if (responseText == "OK") {236                         $("#AccessRights").DataTable().ajax.reload();237                     }238                 },239                 dataType: "json"240             });241         });242     </script>243     @Scripts.Render("~/bundles/jqueryval")244 }
Add View

 

MVC JQuery Table Ajax 的一些扩展和应用