第一次使用easyui配合ajax在.net下的mvc3中做项目,,,我能说我一直被各种人鄙视么???╮(╯_╰)╭,说多了都是泪啊
几乎每一个增删改功能,对我来说,每一步都是新的,一点儿一点儿来,总结:遇到的问题大概有:
<1>、时间格式化显示 <2>、上传文件 <3>、submit提交表单 <4>、加载表单时的数据绑定 <5>、 True和true在js里的区别
<6>、field绑定数据 <7>、json的Data数据的简单操作 <8>、页面返回提示
由于,教师详细信息内容过多,就把详细信息分出来,单独添加,中间牵涉到性别,生日等不同类别的信息的默认选中等,以及文件上传,没少费工夫。
以教师信息管理为例子,总结如下 第一步——>显示列表信息——>添加——>修改——>修改详细——>删除
1、使用easyui显示用户列表,为了让更方便写程序,把js单独拿出来,csthml页面里不再写js,教师信息列表页面如下:
Index.cshtml:
1 @{ 2 ViewBag.Title = "教师信息管理"; 3 Layout = "~/Views/Shared/_Layout2.cshtml"; 4 } 5 <script src="@Url.Content("~/Scripts/BasicSchool_TeacherJS.js")" type="text/javascript"></script> 6 7 <div region="center" style=" 550px; height: 300px; padding: 1px; overflow-y: hidden"> 8 <div id="grid"> 9 </div> 10 </div> 11 <div id="Dlg-Edit" title="窗口" style=" 500px; height: 300px;" buttons="#buttons"> 12 <div style="padding: 20px 20px 40px 40px;"> 13 <form method="post" id="Form1"> 14 <table> 15 <tr> 16 <td style="text-align: right"> 17 登陆账号: 18 </td> 19 <td> 20 <input type="text" name="userName" id="userName" class="easyui-validatebox" required="true" 21 style=" 200px;" maxlength="25" /> 22 (限制:50个字节) 23 </td> 24 </tr> 25 <tr> 26 <td style="text-align: right"> 27 真实姓名: 28 </td> 29 <td> 30 <input type="text" name="RealName" id="RealName" class="easyui-validatebox" required="true" 31 style=" 200px;" /> 32 </td> 33 </tr> 34 <tr> 35 <td style="text-align: right"> 36 密码: 37 </td> 38 <td> 39 <input type="password" name="pwd" id="pwd" class="easyui-validatebox" required="true" 40 style=" 200px;" /> 41 </td> 42 </tr> 43 <tr> 44 <td style="text-align: right"> 45 确认密码: 46 </td> 47 <td> 48 <input type="password" name="pwdAgain" id="pwdAgain" class="easyui-validatebox" required="true" 49 style=" 200px;" /> 50 </td> 51 </tr> 52 </table> 53 </form> 54 </div> 55 </div> 56 <div id="buttons"> 57 <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-ok" onclick="saveData()"> 58 保存</a> <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-cancel" 59 onclick="javascript:$('#Dlg-Edit').dialog('close')">关闭</a> 60 </div> 61 <div id="search-window" title="搜索教师账号信息" style=" 350px; height: 250px; padding: 10px"> 62 <div style="padding: 10px; background: #fff; border: 1px solid #ccc;"> 63 <form method="post" id="Form2"> 64 <table> 65 <tr> 66 <td style="text-align: right"> 67 登陆账号: 68 </td> 69 <td> 70 <input name="lName" id="lName" style=" 150px;" /> 71 </td> 72 </tr> 73 <tr> 74 <td style="text-align: right"> 75 真实姓名: 76 </td> 77 <td> 78 <input name="tName" id="tName" style=" 150px;" /> 79 </td> 80 </tr> 81 </table> 82 </form> 83 </div> 84 <div style="text-align: right; padding: 5px; vertical-align: bottom"> 85 <a href="javascript:void(0)" onclick="SearchOK()" id="btn-search" icon="icon-ok">搜索</a> 86 <a href="javascript:void(0)" onclick="closeSearchWindow()" id="btn-search-cancel" 87 icon="icon-cancel">取消</a> 88 </div> 89 </div> 90 91 <div title="完善教师账号信息" id="Creat_Dialog" style=" 450px; height: 500px;padding: 10px; background: #fff; border: 1px solid #ccc;" /> 92
头部的 <script src="@Url.Content("~/Scripts/BasicSchool_TeacherJS.js")" type="text/javascript"></script>是引入该页面所有的js所在页
最下面的div 是为了完善用户信息所设置的,存放用户详细信息表单
<div title="完善教师账号信息" id="Creat_Dialog" style=" 450px; height: 500px;padding: 10px; background: #fff; border: 1px solid #ccc;" />
具体的详细信息表单放到另外一个页面里TeacherInfoUpload.cshtml
2、js页面:
1 // 全局变量 2 var grid; 3 var dlg_Edit; 4 var dlg_Edit_form; 5 var searchWin; 6 var searchForm; 7 var virpath = ""; //网站的虚拟目录 如:/ShopManager 8 9 var detailsWin; //教师详细信息框 10 var detailsForm;//教师详细信息表单 11 12 13 $(function () { 14 15 DataGirdBind(); //加载数据 16 17 dlg_Edit = $('#Dlg-Edit').dialog({ 18 closed: true, 19 modal: true, 20 toolbar: [{ 21 text: '保存', 22 iconCls: 'icon-save', 23 handler: saveData 24 }, '-', { 25 text: '关闭', 26 iconCls: 'icon-no', 27 handler: function () { 28 dlg_Edit.dialog('close'); 29 } 30 }] 31 }); 32 33 dlg_Edit_form = dlg_Edit.find('form'); 34 35 $('#btn-search,#btn-search-cancel').linkbutton(); 36 searchWin = $('#search-window').window({ 37 iconCls: 'icon-search', 38 closed: true, 39 modal: true 40 }); 41 searchForm = searchWin.find('form'); 42 $('body').layout(); 43 44 //初始化表格参数 -=S=- 45 $('#btn-detail,#btn-detail-cancel').linkbutton(); 46 detailsWin = $('#details').window({ 47 iconCls: 'icon-details', 48 closed: true, 49 modal: true 50 }); 51 detailsForm = detailsWin.find('form'); 52 // -=E=- 53 54 }); 55 56 //初始化Gird表格 57 function DataGirdBind() { 58 grid = $('#grid').datagrid({ 59 title: '管理员列表', 60 iconCls: 'icon-save', 61 methord: 'post', 62 url: '/BasicSchool_TeacherManager/GetList/', 63 sortName: 'id', 64 sortOrder: 'desc', 65 idField: 'id', 66 pageSize: 20, 67 striped: true, //奇偶行是否区分 68 frozenColumns: [[ 69 { field: 'ck', checkbox: true } 70 ]], 71 columns: [[ 72 { field: 'id', title: '编号', 20, sortable: true }, 73 { field: 'userName', title: '教师账号', 50, sortable: true }, 74 { field: 'RealName', title: '真实姓名', 50, sortable: true }, 75 { field: 'pwd', title: '密码', 50, sortable: true }, 76 { field: 'schoolName', title: '学校名称', 50, sortable: true } 77 ]], 78 fit: true, 79 pagination: true, 80 rownumbers: true, 81 fitColumns: true, 82 singleSelect: false, 83 toolbar: [{ 84 text: '新增', 85 iconCls: 'icon-add', 86 handler: add 87 }, '-', { 88 text: '修改', 89 iconCls: 'icon-edit', 90 handler: edit 91 }, '-', { 92 text: '完善详细', 93 iconCls: 'icon-edit', 94 handler: AddData 95 }, '-', { 96 text: '删除', 97 iconCls: 'icon-remove', 98 handler: del 99 }, '-', { 100 text: '高级搜索', 101 iconCls: 'icon-search', 102 handler: OpensearchWin 103 }, '-', { 104 text: '所有', 105 iconCls: 'icon-search', 106 handler: showAll 107 }], onDblClickRow: function (rowIndex, rowData) { //双击事件 108 dlg_Edit.dialog('open'); 109 dlg_Edit_form.form('clear'); //清除之前面选中的表单 110 dlg_Edit.dialog('setTitle', '您正在查看的是:' + rowData.schoolName + "->" + rowData.schoolName); 111 112 dlg_Edit_form.form('load', rowData); //加载到表单的控件上 113 114 dlg_Edit_form.url = virpath + '/BasicSchool_TeacherManager/UpdateSchool?id=' + rowData.id; 115 116 }, onHeaderContextMenu: function (e, field) { 117 e.preventDefault(); 118 if (!$('#tmenu').length) { 119 createColumnMenu(); 120 } 121 $('#tmenu').menu('show', { 122 left: e.pageX, 123 top: e.pageY 124 }); 125 } 126 }); 127 } 128 129 130 //打开添加窗口 131 function AddData() { 132 var rows = grid.datagrid('getSelections'); 133 var num = rows.length; 134 if (num == 0) { 135 Msgshow('请选择一条记录进行操作!'); 136 return; 137 } 138 else if (num > 1) { 139 Msgfade('您选择了多条记录,只能选择一条记录进行修改!'); //$.messager.alert('提示', '您选择了多条记录,只能选择一条记录进行修改!', 'info'); 140 return; 141 } 142 143 var url_str = '/BasicSchool_TeacherManager/TeacherInfoUpload'; 144 145 $('#Creat_Dialog').load(url_str, function () { 146 $(this).dialog({ 147 title: '编辑教师详细信息', 148 modal: true, 149 loadingMessage: '正在加载...', 150 buttons: [{ 151 text: '提交', 152 iconCls: 'icon-ok', 153 handler: function () { 154 $('#FormTeacherInfo').submit(); //提交id为FormTeacherInfo是表单到url_str路径 155 } 156 }, { 157 text: '取消', 158 iconCls: 'icon-cancel', 159 handler: function () { 160 $('#Creat_Dialog').dialog('close'); 161 } 162 }] 163 }); 164 UserInfoVal(); 165 }).show(); 166 } 167 168 169 //编辑AJAX提交 170 function ajaxAdd() { 171 $('#FormTeacherInfo').ajaxSubmit({ 172 url: '/BasicSchool_TeacherManager/TeacherInfoUpload', 173 beforeSubmit: function () { 174 return true; 175 }, 176 success: function (data) { 177 if (data == true) { 178 $('#Creat_Dialog').dialog('close'); 179 $.messager.show({ 180 title: '提示', 181 msg: '保存成功', 182 timeout: 2000, 183 showType: 'slide' 184 }); 185 DataGirdBind(); //重新加载数据[刷新数据列表] 186 } else { 187 data 188 $.messager.show({ 189 title: '提示', 190 msg: '保存失败:' + data.msg, 191 timeout: 0, 192 showType: 'slide' 193 }); 194 } 195 } 196 }); 197 return false; 198 } 199 200 //加载用户数据 201 function UserInfoVal() { 202 var rows = grid.datagrid('getSelections'); 203 204 205 detailsForm.form('clear'); 206 detailsWin.dialog('open'); 207 detailsWin.dialog('setTitle', '您正在完善的是:' + rows[0].userName + "->" + rows[0].userName); 208 var idD = rows[0].isDirector; //是否是班主任 209 if (idD == "True") { 210 $("#isDirector").attr("checked", true); 211 } 212 else { 213 $("#isDirector").attr("checked", false); 214 } 215 216 $("#titles").val(rows[0].titles); 217 $("#phone").val(rows[0].phone); 218 $("#uName").val(rows[0].userName); 219 $("#birthday").val(formatDate('y-m-d', rows[0].birthday)); //格式化输出日期 220 221 var iSex = rows[0].sex; //性别 222 if (iSex == "True") { 223 $("#rdIsMan").attr("checked", true); 224 } 225 else { 226 $("#rdIsWoman").attr("checked", true); 227 } 228 $("#email").val(rows[0].email); 229 $("#blogUrl").val(rows[0].blogUrl); 230 $("#motto").val(rows[0].motto); 231 var isAct = rows[0].isActivation; //是否是活跃用户 232 if (isAct == "True") { 233 $("#isActivation").attr("checked", true); 234 } else { 235 $("#isActivation").attr("checked", false); 236 } 237 $("#photoOld").val(rows[0].photo); 238 //用户已经有图片,显示 239 if (rows[0].photo != "") { 240 $("#imgPhoto").attr("src", ".." + rows[0].photo); 241 } 242 } 243 244 //格式化时间格式 245 function formatDate(formatStr, fdate) { 246 var fTime, fStr = 'ymdhis'; 247 if (!formatStr) 248 formatStr = "y-m-d h:i:s"; 249 if (fdate) 250 fTime = new Date(fdate); 251 else 252 fTime = new Date(); 253 var formatArr = [ 254 fTime.getFullYear().toString(), 255 (fTime.getMonth() + 1).toString(), 256 fTime.getDate().toString(), 257 fTime.getHours().toString(), 258 fTime.getMinutes().toString(), 259 fTime.getSeconds().toString() 260 ] 261 for (var i = 0; i < formatArr.length; i++) { 262 formatStr = formatStr.replace(fStr.charAt(i), formatArr[i]); 263 } 264 return formatStr; 265 } 266 267 function createColumnMenu() { 268 var tmenu = $('<div id="tmenu" style="100px;"></div>').appendTo('body'); 269 var fields = grid.datagrid('getColumnFields'); 270 for (var i = 0; i < fields.length; i++) { 271 $('<div iconCls="icon-ok"/>').html(fields[i]).appendTo(tmenu); 272 } 273 tmenu.menu({ 274 onClick: function (item) { 275 if (item.iconCls == 'icon-ok') { 276 grid.datagrid('hideColumn', item.text); 277 tmenu.menu('setIcon', { 278 target: item.target, 279 iconCls: 'icon-empty' 280 }); 281 } else { 282 grid.datagrid('showColumn', item.text); 283 tmenu.menu('setIcon', { 284 target: item.target, 285 iconCls: 'icon-ok' 286 }); 287 } 288 } 289 }); 290 } 291 292 function getSelectedArr() { 293 var ids = []; 294 var rows = grid.datagrid('getSelections'); 295 for (var i = 0; i < rows.length; i++) { 296 ids.push(rows[i].id); 297 } 298 return ids; 299 } 300 function getSelectedID() { 301 var ids = getSelectedArr(); 302 return ids.join(','); 303 } 304 function arr2str(arr) { 305 306 return arr.join(','); 307 } 308 309 function add() { 310 dlg_Edit_form.form('clear'); 311 dlg_Edit.dialog('open'); 312 dlg_Edit.dialog('setTitle', '添加教师'); 313 $('#Enable').combobox('setValue', true); //默认设置开启 314 dlg_Edit_form.url = virpath + '/BasicSchool_TeacherManager/AddSchoolManager/'; 315 } 316 function edit() { 317 var rows = grid.datagrid('getSelections'); 318 var num = rows.length; 319 if (num == 0) { 320 Msgshow('请选择一条记录进行操作!'); 321 return; 322 } 323 else if (num > 1) { 324 Msgfade('您选择了多条记录,只能选择一条记录进行修改!'); //$.messager.alert('提示', '您选择了多条记录,只能选择一条记录进行修改!', 'info'); 325 return; 326 } 327 else { 328 dlg_Edit_form.form('clear'); 329 dlg_Edit.dialog('open'); 330 dlg_Edit.dialog('setTitle', '您正在修改的是:' + rows[0].schoolName + "->" + rows[0].schoolName); 331 dlg_Edit_form.form('load', rows[0]); //加载到表单的控件上 332 dlg_Edit_form.url = virpath + '/BasicSchool_TeacherManager/UpdateSchool?id=' + rows[0].id; 333 } 334 } 335 336 function del() { 337 var arr = getSelectedArr(); 338 if (arr.length > 0) { 339 $.messager.confirm('提示信息', '您确认要删除选中的记录吗?', function (data) { 340 if (data) { 341 $.ajax({ 342 url: virpath + '/BasicSchool_TeacherManager/DeleteSchool?ids=' + arr2str(arr), 343 type: 'post', 344 error: function () { 345 Msgalert('错误', '删除失败!', 'error'); 346 grid.datagrid('clearSelections'); 347 }, 348 success: function (re) { 349 var data = eval('(' + re + ')'); 350 if (data.success) { 351 Msgfade(arr.length + "条记录" + data.msg); //提示消息 352 grid.datagrid('reload'); 353 grid.datagrid('clearSelections'); //清除所有选中的元素 354 } else { 355 Msgalert('错误', data.msg, 'error'); 356 } 357 } 358 }); 359 } 360 }); 361 } else { 362 Msgshow('请先选择要删除的记录。'); 363 } 364 } 365 function saveData() { 366 dlg_Edit_form.form('submit', { 367 url: dlg_Edit_form.url, 368 onSubmit: function () { 369 return $(this).form('validate'); 370 }, 371 success: successCallback 372 }); 373 } 374 375 376 function showAll() { 377 grid.datagrid({ url: virpath + '/BasicSchool_TeacherManager/GetList/' }); 378 } 379 function OpensearchWin() { 380 searchWin.window('open'); 381 searchForm.form('clear'); 382 $('#Enable2').combobox('setValue', true); //默认设置开启搜素 383 } 384 385 function SearchOK() { 386 var lName = $("#lName").val(); 387 var tName = $("#tName").val(); 388 searchWin.window('close'); 389 grid.datagrid({ url: virpath + '/BasicSchool_TeacherManager/Search/', queryParams: { lName: lName, tName: tName} }); 390 //经过测试queryParams参数可以提交到后台通过FormCollection获取 也可以Request["ProductName"]=?获取 391 } 392 393 function closeSearchWindow() { 394 searchWin.window('close'); 395 } 396 function closeDetailWindow() { 397 detailsWin.window('close'); 398 }
<1>、时间格式化问题:js里的方法
var rows = grid.datagrid('getSelections'); 获取Grid当前行的数据,
<5>、 True 和true是有区别的,true是bool,而True就是个字符串,如果js里使用if else语句,如果条件不符合if,那么不管它符合不符合else,一定会执行else,所以要注意if条件表达式的写法,是否正确。
<4>、对于checkbox,或者是radio的赋值,使用$("#id").attr("checked", true);即可,如果是其它赋值,都可以使用这种方式,只需要把对应属性换掉即可,如,给img标签指定图片路径:$("#imgPhoto").attr("src", ".." + rows[0].photo);
<2>、在加载详细信息div时,指定form表单请求路径,在Action里指向该页面,就体现到下面TeacherInfoUpload.cshtml页面的存在价值了。打开页面的同时,把本页面的当前选中行数据绑定。
<3>、js里的方法:ajaxAdd(),提交表单的方法,
上传的时候使用Form表单上传的话,后台无法获取文件的值,只能用submit把整个表单传到后台,而使用submit提交的话,Action又无法返回列表页面,所以把表单内容单独提取出来,放到一个页面里,然后通过js中的方法到于该页面同名的Action中,加载这个form表单,在表单提交时,调用js中的提交方法,方法中到指定的Action中操作数据,然后返回json数据的同时,重新加载列表页面,即可。
<8>、提交方法:ajaxAdd(),中的Success获取action返回的json数据Data值,根据Data值判断,成功或者是失败,失败提示信息msg 是在action中定义过的
3、Controller页面:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.Mvc; 6 using TeachAid.SpecialCloudEduPlatform.BLL; 7 using TeachAid.SpecialCloudEduPlatform.Entity; 8 using System.Web.Script.Serialization; 9 using Newtonsoft.Json; 10 using System.IO; 11 12 namespace TeachAid.SpecialCloudEduPlatform.Web.Controllers 13 { 14 public class BasicSchool_TeacherManagerController : Controller 15 { 16 // 17 // GET: /BasicSchool_TeacherManager/ 18 19 BLLBasicMain_UserInfo userInfoBLL = new BLLBasicMain_UserInfo(); 20 BLLBasicMain_SchoolInfo schoolBLL = new BLLBasicMain_SchoolInfo(); 21 BLLJsonHelper bjb = new BLLJsonHelper(); 22 BLLBasicSchool_Teacher teacherBLL = new BLLBasicSchool_Teacher(); 23 public ActionResult Index() 24 { 25 return View(); 26 } 27 28 /// <summary> 29 /// 获取某学校所有管理员 30 /// </summary> 31 /// <returns></returns> 32 public ActionResult GetList() 33 { 34 #region MyRegion 35 //Dictionary<string, object> dic = new Dictionary<string, object>(); 36 37 //string lName = null; string rName = null; int sId = 0; 38 //if (!string.IsNullOrEmpty(Request.Form["lName"])) lName = Request.Form["lName"].ToString(); 39 //if (!string.IsNullOrEmpty(Request.Form["tName"])) rName = Request.Form["tName"].ToString(); 40 //if (!string.IsNullOrEmpty(Request.Form["TypeId2"])) sId = Convert.ToInt32(Request.Form["TypeId2"]); 41 //SchoolUserInfoData userInfoData = new SchoolUserInfoData(); 42 //int pageIndex = int.Parse(Request.Form["page"].ToString()); 43 //int pageSize = int.Parse(Request.Form["rows"].ToString()); 44 //var userListByParam = userInfoBLL.GetUserTeacherInfoBySchoolAndRold(((BasicMainUserInfo)Session["UserInfoLogin"]).schoolID, 1); 45 ////转换成 46 //var uParam = userListByParam.Select(a => new 47 //{ 48 // schoolName = a.schoolInfo.schoolName, 49 // id = a.id, 50 // userName = a.userName, 51 // RealName = a.RealName, 52 // pwd = a.pwd, 53 // lTitle = a.teacherInfo.titles, 54 // tPhone = a.teacherInfo.phone, 55 // rdIsDirector = a.teacherInfo.isDirector, 56 // tBirth = a.teacherInfo.birthday, 57 // rdIsMan = a.teacherInfo.sex, 58 // tEmail = a.teacherInfo.email, 59 // tBlog = a.teacherInfo.blogUrl, 60 // tMotto = a.teacherInfo.motto, 61 // fileTeacherPhoto = a.teacherInfo.photo, 62 // rdIsEnable = a.teacherInfo.isActive 63 //}).ToList(); 64 65 //dic.Add("total", uParam.Count); 66 //dic.Add("rows", uParam.Skip(pageSize * (pageIndex - 1)).Take(pageSize)); 67 //return Json(dic); 68 #endregion 69 70 int pageIndex = int.Parse(Request.Form["page"].ToString()); 71 int pageSize = int.Parse(Request.Form["rows"].ToString()); 72 string biao = "View_BasicSchool_UserTeacherDetails"; 73 string zhid = "id,userName,RealName,pwd,types,schoolID,schoolName,bid,cId,basicMain_UserInfoID,basicMain_SchoolId,loginAccount,cRName,cPwd,isDirector,titles,birthday,phone,sex,email,blogUrl,motto,photo,isActivation,addTime"; 74 string str = " schoolID=" + ((BasicMainUserInfo)Session["UserInfoLogin"]).schoolID + " and types=1 "; 75 string json = bjb.GetJSON(pageIndex, pageSize, biao, zhid, "id", "desc", str); 76 return Content(json, "text/html;charset=UTF-8"); 77 } 78 79 /// <summary> 80 /// 添加一个对象 81 /// </summary> 82 /// <param name="collection"></param> 83 /// <returns></returns> 84 public ActionResult AddSchoolManager(FormCollection collection) 85 { 86 int result = 0; 87 BasicMainUserInfo userInfo = new BasicMainUserInfo(); 88 userInfo.userName = Convert.ToString(collection.Get("userName")); 89 userInfo.RealName = Convert.ToString(collection.Get("RealName")); //根据表单里控件Name获取值 90 userInfo.pwd = Convert.ToString(collection.Get("pwd")); //密码 91 userInfo.schoolID = ((BasicMainUserInfo)Session["UserInfoLogin"]).schoolID; //学校ID 92 userInfo.typeId = 1; //用户类别 1:教师 93 94 Message msg; 95 96 string againPwd = Convert.ToString(collection.Get("pwdAgain")); 97 if (userInfo.pwd != againPwd) 98 { 99 msg = new Message(false, "两次输入密码不一致,请重新输入"); 100 } 101 else 102 { 103 result = userInfoBLL.IsExist(Convert.ToString(collection.Get("userName"))); 104 if (result != 0) 105 { 106 msg = new Message(false, "登录名已经存在,请重新输入"); 107 } 108 else 109 { 110 if (userInfoBLL.AddUserInfo(userInfo) != 0) 111 { 112 msg = new Message(true, "添加信息成功!"); 113 } 114 else 115 { 116 msg = new Message(false, "添加失败!"); 117 } 118 } 119 } 120 return Content(JsonConvert.SerializeObject(msg), "text/html;charset=UTF-8"); 121 } 122 123 /// <summary> 124 /// 查询用户名称是否有重复 125 /// </summary> 126 /// <param name="collection"></param> 127 /// <returns></returns> 128 public ActionResult IsExist(FormCollection collection) 129 { 130 int result = 0; 131 string name = Request.Form["schoolName"].ToString(); 132 result = userInfoBLL.IsExist(name); 133 Message msg; 134 if (result != 0) 135 { 136 msg = new Message(false, "用户登录名已存在,请重新输入"); 137 } 138 else 139 { 140 msg = new Message(true, "用户名输入有效"); 141 } 142 return Content(JsonConvert.SerializeObject(msg), "text/html;charset=UTF-8"); 143 } 144 145 /// <summary> 146 /// 修改一个对象 147 /// </summary> 148 /// <param name="id"></param> 149 /// <param name="collection"></param> 150 /// <returns></returns> 151 public ActionResult UpdateSchool(int id, FormCollection collection) 152 { 153 int result = 0; 154 BasicMainUserInfo model = new BasicMainUserInfo(); 155 model.id = id; 156 model.userName = Convert.ToString(collection.Get("userName")); 157 model.RealName = Convert.ToString(collection.Get("RealName")); 158 model.pwd = Convert.ToString(collection.Get("pwd")); 159 model.schoolID = ((BasicMainUserInfo)Session["UserInfoLogin"]).schoolID; 160 model.typeId = 1; //用户类别 1:教师 161 Message msg; 162 163 string pwdAgain = Convert.ToString(collection.Get("pwdAgain")); 164 if (pwdAgain != model.pwd) 165 { 166 msg = new Message(false, "两次密码输入不一致,请重新输入!"); 167 } 168 169 result = userInfoBLL.IsExist(Convert.ToString(collection.Get("realName"))); 170 if (result != 0) 171 { 172 msg = new Message(false, "登录名已经存在,请重新输入"); 173 } 174 else 175 { 176 if (userInfoBLL.UpdateUserInfo(model) != 0) 177 { 178 msg = new Message(true, "修改信息成功!"); 179 } 180 else 181 { 182 msg = new Message(false, "修改信息成功!"); 183 } 184 } 185 return Content(JsonConvert.SerializeObject(msg), "text/html;charset=UTF-8"); 186 } 187 188 /// <summary> 189 /// 删除对象 190 /// </summary> 191 /// <param name="ids">对象id列表</param> 192 /// <returns></returns> 193 public ActionResult DeleteSchool(string ids) 194 { 195 string[] deleId = ids.Split(','); 196 Message msg; 197 198 int res = 0; 199 for (int i = 0; i < deleId.Length; i++) 200 { 201 if (userInfoBLL.DeleteUserInfo(Convert.ToInt32(deleId[i])) > 0) 202 { 203 res++; 204 } 205 } 206 207 if (res == deleId.Length) 208 { 209 msg = new Message(true, "数据删除成功!"); 210 } 211 else 212 { 213 msg = new Message(false, "数据删除失败,请重试!"); 214 } 215 return Content(JsonConvert.SerializeObject(msg), "text/html;charset=UTF-8"); 216 } 217 218 /// <summary> 219 /// 根据条件查询用户信息 220 /// </summary> 221 /// <returns></returns> 222 public ActionResult Search() 223 { 224 Dictionary<string, object> dic = new Dictionary<string, object>(); 225 226 string lName = null; string rName = null; int sId = 0; 227 if (!string.IsNullOrEmpty(Request.Form["lName"])) lName = Request.Form["lName"].ToString(); 228 if (!string.IsNullOrEmpty(Request.Form["tName"])) rName = Request.Form["tName"].ToString(); 229 if (!string.IsNullOrEmpty(Request.Form["TypeId2"])) sId = Convert.ToInt32(Request.Form["TypeId2"]); 230 SchoolUserInfoData userInfoData = new SchoolUserInfoData(); 231 int pageIndex = int.Parse(Request.Form["page"].ToString()); 232 int pageSize = int.Parse(Request.Form["rows"].ToString()); 233 var userListByParam = userInfoBLL.GetUserListByPara(lName, rName, sId); 234 235 //转换成 236 var uParam = userListByParam.Select(a => new 237 { 238 schoolName = a.schoolInfo.schoolName, 239 id = a.id, 240 userName = a.userName, 241 RealName = a.RealName, 242 pwd = a.pwd 243 }).ToList(); 244 245 dic.Add("total", uParam.Count); 246 dic.Add("rows", uParam.Skip(pageSize * (pageIndex - 1)).Take(pageSize)); 247 248 return Json(dic); 249 } 250 251 252 public ActionResult test() 253 { 254 return View(); 255 } 256 257 258 /// <summary> 259 /// 中间Action 由于本页面的submit按钮提交表单后,直接返回本页面定义一个中间Action,由此Action返回到对应页面,在页面中通过Ajax 260 /// 方法,把数据post提交到本页面中的处理方法中,进行数据处理,并提交数据 261 /// </summary> 262 /// <returns></returns> 263 public ActionResult TeacherInfoUpload() 264 { 265 //跳转到指定view 该TeacherInfoUpload视图必须是真实存在于view文件夹中 266 return View(); 267 } 268 269 270 [HttpPost] 271 public JsonResult TeacherInfoUpload(FormCollection form) 272 { 273 #region 获取用户信息 274 BasicSchoolTeacher teacherInfo = new BasicSchoolTeacher(); 275 if (!string.IsNullOrEmpty(form.Get("birthday"))) 276 teacherInfo.birthday = Convert.ToDateTime(form.Get("birthday")).ToShortDateString(); 277 if (!string.IsNullOrEmpty(form.Get("blogUrl"))) 278 teacherInfo.blogUrl = form.Get("blogUrl").ToString(); 279 if (!string.IsNullOrEmpty(form.Get("email"))) 280 teacherInfo.email = form.Get("email").ToString(); 281 if (!string.IsNullOrEmpty(form.Get("motto"))) 282 teacherInfo.motto = form.Get("motto").ToString(); 283 if (!string.IsNullOrEmpty(form.Get("phone"))) 284 teacherInfo.phone = form.Get("phone").ToString(); 285 if (!string.IsNullOrEmpty(form.Get("titles"))) 286 teacherInfo.titles = form.Get("titles").ToString(); 287 teacherInfo.addTime = DateTime.Now.ToShortDateString(); 288 289 #region bool值判断 290 if (!string.IsNullOrEmpty(form.Get("isDirector"))) 291 { 292 if (form.Get("isDirector").ToString().Contains('1')) { teacherInfo.isDirector = true; } 293 } 294 else teacherInfo.isDirector = false; 295 if (!string.IsNullOrEmpty(form.Get("sex"))) 296 teacherInfo.sex = form.Get("sex").ToString() == "0" ? true : false; //0:男;1:女 297 else teacherInfo.sex = false; 298 if (!string.IsNullOrEmpty(form.Get("isActivation"))) 299 teacherInfo.isActive = form.Get("isActivation").ToString() == "1" ? true : false; 300 else teacherInfo.isActive = false; 301 #endregion 302 303 #region 根据登录名查询当前要完善用户唯一对象,并把相关信息赋值给教师详细信息 304 BasicMainUserInfo userInfo = (userInfoBLL.GetUserListByPara(form.Get("uName").ToString(), "", ((BasicMainUserInfo)Session["UserInfoLogin"]).schoolID))[0]; 305 teacherInfo.basicMain_SchoolId = userInfo.schoolID; 306 teacherInfo.basicMain_UserInfoID = userInfo.id; //用户对应的用户表中的ID 307 teacherInfo.loginAccount = userInfo.userName; 308 teacherInfo.pwd = userInfo.pwd; 309 teacherInfo.realName = userInfo.RealName; 310 #endregion 311 #endregion 312 313 #region 图片格式验证 314 string[] extens = new string[] { ".jpeg", ".bmp", ".png", ".gif", ".jpg" }; //定义几种文件格式 315 #endregion 316 317 int result; //结果 318 BasicSchoolTeacher model = new BasicSchoolTeacher(); 319 model = teacherBLL.GetTeacherModelByAccount(form.Get("uName").ToString()); 320 321 #region 操作 322 //修改 323 if (model != null && model.basicMain_UserInfoID != 0) 324 { 325 //如果用户有上传,则删除原有图片,没有则不上传 326 if (Request.Files.Count > 0) 327 { 328 string fileName = Request.Files[0].FileName; //获取当前文件名 329 string ext = Path.GetExtension(fileName); 330 //验证文件格式 331 if (extens.Contains(ext)) 332 { 333 //生成以时间为随机数的新文件名 334 string newName = DateTime.Now.ToString("yyyyMMddHHmmss") + DateTime.Now.Millisecond.ToString() + "_" + new Random().Next(10, 99).ToString() + ext; 335 336 //文件大小不为0 337 HttpPostedFileBase fileUp = Request.Files[0]; 338 //服务器上的UpLoadFile文件夹必须有读写权限 339 fileUp.SaveAs(Server.MapPath(@"~/UploadFile/PersonImg/" + newName)); 340 341 teacherInfo.photo = @"/UploadFile/PersonImg/" + newName; //为文件重新命名 342 } 343 else 344 { 345 return Json(new Message(false, "图片格式不正确,支持.jpeg、.bmp、.png、.gif、.jpg几种格式!")); 346 } 347 } 348 else 349 { 350 teacherInfo.photo = form.Get("photoOld").ToString(); 351 } 352 teacherInfo.id = model.id; 353 354 result = teacherBLL.UpdateTeacher(teacherInfo); 355 } 356 else 357 { 358 //如果用户有上传,则删除原有图片,没有则不上传 359 if (Request.Files.Count > 0) 360 { 361 string fileName = Request.Files[0].FileName; //获取当前文件名 362 string ext = Path.GetExtension(fileName); 363 364 //验证文件格式 365 if (extens.Contains(ext)) 366 { 367 //生成以时间为随机数的新文件名 368 string newName = DateTime.Now.ToString("yyyyMMddHHmmss") + DateTime.Now.Millisecond.ToString() + "_" + new Random().Next(10, 99).ToString() + ext; 369 370 //文件大小不为0 371 HttpPostedFileBase fileUp = Request.Files[0]; 372 //保存成自己的文件全路径,newfile就是你上传后保存的文件, 373 //服务器上的UpLoadFile文件夹必须有读写权限 374 fileUp.SaveAs(Server.MapPath(@"~/UploadFile/PersonImg/" + newName)); 375 376 teacherInfo.photo = @"/UploadFile/PersonImg/" + newName; //为文件重新命名 377 } 378 else 379 { 380 return Json(new Message(false, "图片格式不正确,支持.jpeg、.bmp、.png、.gif、.jpg几种格式!")); 381 } 382 } 383 else 384 { 385 teacherInfo.photo = ""; 386 } 387 result = teacherBLL.AddTeacherModel(teacherInfo); //修改用户信息 388 } 389 #endregion 390 391 JsonResult json = new JsonResult(); //执行结果返回 392 if (result != 0) 393 { 394 json.Data = true; 395 } 396 else 397 { 398 json.Data = false; 399 } 400 return json; 401 } 402 } 403 }
<8>、Controller中的Action:TeacherInfoUpload 指定json的返回值为:return Json(new Message(false, "图片格式不正确,支持.jpeg、.bmp、.png、.gif、.jpg几种格式!")); json的Data属性的两个值,这样即可。
4、教师详细信息编辑Form表单 存放用户详细信息的表单,
1 @{ 2 Layout = null; 3 } 4 <script type="text/javascript"> 5 6 $(function () { 7 //这里写新建时初始化控件的值 8 //入库表单校验 9 $("#FormTeacherInfo").validate({ 10 submitHandler: function (form) { 11 ajaxAdd(); 12 } 13 }); 14 }); 15 16 </script> 17 @using (Html.BeginForm("TeacherInfoUpload", "BasicSchool_TeacherManager", FormMethod.Post, new { id = "FormTeacherInfo", enctype = "multipart/form-data" })) 18 { 19 <fieldset> 20 <table> 21 <tr> 22 <td style="text-align: right"> 23 职称: 24 </td> 25 <td> 26 <input name="titles" id="titles" style=" 150px;" required="true" /> 27 <input type="hidden" id="uName" name="uName" /> 28 </td> 29 </tr> 30 <tr> 31 <td style="text-align: right"> 32 联系电话: 33 </td> 34 <td> 35 <input name="phone" id="phone" style=" 150px;" required="true" /> 36 </td> 37 </tr> 38 <tr> 39 <td style="text-align: right"> 40 是否是班主任: 41 </td> 42 <td> 43 <input id="isDirector" name="isDirector" type="checkbox" value="1" /> 44 </td> 45 </tr> 46 <tr> 47 <td style="text-align: right"> 48 生日: 49 </td> 50 <td> 51 <input name="birthday" id="birthday" style=" 150px;" required="true" onclick="WdatePicker({skin:'default'})" /> 52 </td> 53 </tr> 54 <tr> 55 <td style="text-align: right"> 56 性别: 57 </td> 58 <td> 59 <input id="rdIsMan" name="sex" type="radio" value="0" />男 60 <input id="rdIsWoman" name="sex" type="radio" value="1" />女 61 </td> 62 </tr> 63 <tr> 64 <td style="text-align: right"> 65 邮箱: 66 </td> 67 <td> 68 <input name="email" id="email" style=" 150px;" required="true" /> 69 </td> 70 </tr> 71 <tr> 72 <td style="text-align: right"> 73 个人博客: 74 </td> 75 <td> 76 <input name="blogUrl" id="blogUrl" style=" 150px;" required="true" /> 77 </td> 78 </tr> 79 <tr> 80 <td style="text-align: right"> 81 个人座右铭: 82 </td> 83 <td> 84 <input name="motto" id="motto" style=" 150px;" required="true" /> 85 </td> 86 </tr> 87 <tr> 88 <td style="text-align: right"> 89 用户状态: 90 </td> 91 <td> 92 <input id="isActivation" name="isActivation" type="checkbox" value="1" />启用 93 </td> 94 </tr> 95 <tr> 96 <td style="text-align: right ; 150px;"> 97 形象照片: 98 <input name="photoOld" type="hidden" id="photoOld" /> 99 </td> 100 <td> 101 <img id="imgPhoto" style="border: 1px solid CCC; 100px; height:100px;" /> 102 <input name="photo" type="file" id="photo" /> 103 <span style=" font-size:12px; color:gray;">仅支持.jpeg、.bmp、.png、.gif、.jpg格式</span> 104 </td> 105 </tr> 106 </table> 107 </fieldset> 108 }
该静态页面中的@using (Html.BeginForm("TeacherInfoUpload", "BasicSchool_TeacherManager", FormMethod.Post, new { id = "FormTeacherInfo", enctype = "multipart/form-data" })){}
指定要把表单数据提交到那个Controller里的Action中去执行,并且指定表单id,提交方法为post
并在页面上方指定该表单提交到哪个方法:
太乱了,,不知道过两天自己能不能看懂。。。