这次我是在EasyUI中使用了KindEditor的编辑器,按照官方给的代码,总是无法获取编辑器里面的值(内容),如下: KindEditor.ready(function (K) { var editor1 = K.create(‘#content’, { cssPath: ‘../js/plugins/code/prettify.css’, uploadJson: ‘upload_json.ashx’, fileManagerJson: ‘file_manager_json.ashx’, allowFileManager: true, afterCreate: function () { var self = this; K.ctrl(document, 13, function () { self.sync(); K(‘form[name=example]’)[0].submit(); }); K.ctrl(self.edit.doc, 13, function () { self.sync(); K(‘form[name=example]’)[0].submit(); }); } }); prettyPrint();
});
改代码就是官方给的,后来发现,第二次提交,这个content又有值了,甚是奇怪,后来在百度的帮助下,找到了原因,原理是需要在提交之前,异步一下编辑器的内容,改良后的代码如下: KindEditor.ready(function (K) { var editor1 = K.create(‘#content’, { cssPath: ‘../js/plugins/code/prettify.css’, uploadJson: ‘upload_json.ashx’, fileManagerJson: ‘file_manager_json.ashx’, allowFileManager: true, afterCreate: function () { var self = this; K.ctrl(document, 13, function () { self.sync(); K(‘form[name=example]’)[0].submit(); }); K.ctrl(self.edit.doc, 13, function () { self.sync(); K(‘form[name=example]’)[0].submit(); }); }, afterBlur: function () { this.sync(); }//这一步非常重要,如果遗漏,则后台无法接收到数据。
}); prettyPrint();
});
这样后台就可以正常接收数据了,下面是完整代码,也可以下载附件来看:
本次经验分享到此结束,转载请保留原作者地址以及姓名(本人无偿分享经验,有偿接单制作Android或者IOS平台的APP,有需要可以联系我。);
作者:南宫萧尘 E-mail:314791147@qq.comQQ:314791147日期:2016-04-29
<%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”MOOCEducationManagement.aspx.cs” Inherits=”Web.Admin.MOOCEducationManagement” %><!DOCTYPE html><html xmlns=”http://www.w3.org/1999/xhtml”><head runat=”server”> <meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ /> <title>MOOC教学</title> <link rel=”stylesheet” type=”text/css” href=”../css/common.css” /> <link rel=”stylesheet” type=”text/css” href=”../css/admin.css” /> <link rel=”stylesheet” type=”text/css” href=”../js/My97DatePicker/skin/WdatePicker.css” /> <link rel=”stylesheet” type=”text/css” href=”../js/jquery-easyui-1.4.3/themes/bootstrap/easyui.css” /> <link rel=”stylesheet” type=”text/css” href=”../js/jquery-easyui-1.4.3/themes/icon.css” /> <link rel=”stylesheet” href=”../js/plugins/code/prettify.css” /> <style type=”text/css”> a { color: red; } .resource { width: 800px; } </style></head><body> <div id=”top” class=”top”> <div class=”topMenu”> <div class=”topIcon”> <a title=”返回后台首页” href=”index.aspx”> <img src=”../img/home.png” alt=”返回后台首页” /></a> <div class=”line” style=”color: white; font-size: 18px; height: 10px; line-height: 10px; margin-top: -20px;”> <a href=”index.aspx” style=”color: white;”>主页</a> </div> </div> <div class=”topIcon”> <a title=”退出登陆” href=”../index.aspx”> <img src=”../img/exit.png” alt=”退出登陆” /></a> <div class=”line” style=”color: white; font-size: 18px; height: 10px; line-height: 10px; margin-top: -20px;”> <a href=”../index.aspx” style=”color: white;”>退出</a> </div> </div> <div class=”topCloum”> </div> <div class=”topIcon” style=”margin-left: 50px; margin-top: 20px;”> <div class=”line” style=”height: 70px;”> <img src=”../img/pic.png” /> </div> <div class=”line” style=”height: 40px; text-align: left; color: white; font-weight: bold; line-height: 35px; text-indent: 10px; font-size: 18px;”> <asp:Label ID=”lbUserName” runat=”server” Text=”Admin”></asp:Label> </div> </div> </div> </div> <div id=”center” class=”center” style=”background: url(../img/bookMain.png) 0 0 repeat;”> <div id=”lineForDataGrid” class=”line”> <table id=”tt” style=”width: 100%; height: 600px; $(this).width() * 0.2;”> </table> </div> </div> <div id=”bottom” class=”bottom” style=”background: url(../img/bookBottom.png) 0 0 no-repeat;”> MOOC教学 </div> <div id=”dlg” class=”easyui-dialog” style=”width: 350px; height: 200px; padding: 5px 10px” data-options=”closed:true,buttons:’#dlg-buttons’,modal:true”> <form id=”dlg_form” method=”post”> <div class=”fitem”> <label>实训名称:</label> <input name=”name” id=”name” class=”easyui-textbox” required=”true” /> </div> <div class=”fitem”> <label>备注:</label> <input name=”remark” id=”remark” class=”easyui-textbox” data-options=”multiline:true” style=”width: 220px; height: 70px;” /> </div> </form> </div> <div id=”dlg-buttons”> <a href=”javascript:void(0)” class=”easyui-linkbutton” iconcls=”icon-ok” onclick=”fSaveData()”>保存 </a> <a href=”javascript:void(0)” class=”easyui-linkbutton” iconcls=”icon-cancel” onclick=”javascript:$(‘#dlg’).dialog(‘close’)”>取消 </a> </div> <%–资源管理开始–%> <div id=”Resourcedlg” class=”easyui-dialog” style=”width: 850px; height: 550px;” data-options=”closed:true,modal:true”> <div class=”line”> <table id=”ttResource” style=”width: 100%; height: 500px; $(this).width() * 0.2;”> </table> </div> <div id=”dlgForResource” class=”easyui-dialog” style=”width: 850px; height: 530px; padding: 5px 10px” data-options=”closed:true,buttons:’#dlgForResource-buttons’,modal:true”> <form id=”dlg_formForResource” method=”post”> <div class=”fitem resource”> <label>实训类型:</label> <input name=”trainingTypeId” id=”trainingTypeId” class=”easyui-combobox” required=”true” data-options=”valueField:’id’,textField:’name’,editable:false” /> </div> <div class=”fitem resource”> <label>资源名称:</label> <input name=”trainingName” id=”trainingName” class=”easyui-textbox” required=”true” /> </div> <div class=”fitem resource”> <label>缩略图:</label> <input name=”pic” id=”pic” class=”easyui-filebox” data-options=”buttonText: ‘选择文件’,buttonAlign: ‘right'” style=”width: 200px;” /> </div> <div class=”fitem resource”> <label style=”float: left; line-height: 350px;”>资源内容:</label> <%–<input name=”content” id=”content” class=”easyui-textbox” data-options=”multiline:true” style=”width: 700px; height: 350px;” />–%> <input type=”text” name=”content” id=”content” style=”width: 720px; height: 350px; float: right;” /> </div> </form> </div> <div id=”dlgForResource-buttons”> <a href=”javascript:void(0)” class=”easyui-linkbutton” iconcls=”icon-ok” onclick=”fSaveResourceData()”>保存 </a> <a href=”javascript:void(0)” class=”easyui-linkbutton” iconcls=”icon-cancel” onclick=”javascript:$(‘#dlgForResource’).dialog(‘close’)”>取消 </a> </div> </div> <%–资源管理结束–%> <script src=”../js/jquery-1.11.0.js” type=”text/javascript” charset=”utf-8″></script> <script src=”../js/My97DatePicker/WdatePicker.js” type=”text/javascript” charset=”utf-8″></script> <script src=”../js/jquery-easyui-1.4.3/jquery.easyui.min.js” type=”text/javascript”></script> <script src=”../js/jquery-easyui-1.4.3/locale/easyui-lang-zh_CN.js” type=”text/javascript”></script> <script charset=”utf-8″ src=”../js/kindeditor-all.js”></script> <script charset=”utf-8″ src=”../js/lang/zh-CN.js”></script> <script charset=”utf-8″ src=”../js/plugins/code/prettify.js”></script> <script> KindEditor.ready(function (K) { var editor1 = K.create(‘#content’, { cssPath: ‘../js/plugins/code/prettify.css’, uploadJson: ‘upload_json.ashx’, fileManagerJson: ‘file_manager_json.ashx’, allowFileManager: true, afterCreate: function () { var self = this; K.ctrl(document, 13, function () { self.sync(); K(‘form[name=example]’)[0].submit(); }); K.ctrl(self.edit.doc, 13, function () { self.sync(); K(‘form[name=example]’)[0].submit(); }); }, afterBlur: function () { this.sync(); }//这一步非常重要,如果遗漏,则后台无法接收到数据。 }); prettyPrint(); }); </script> <script src=”../js/common.js”></script> <script type=”text/javascript”> var vTrainingTypeID = 0; $(function () { var vWindowHeight = document.body.scrollHeight; var vCenterHeight = vWindowHeight – 131 – 82; $(“#center”).height(vCenterHeight); var vMargionTop = (vCenterHeight – 360) / 2; $(“.centerBook”).css(“margin-top”, vMargionTop); fLoadTable();//加载参数 fLoadResourceTable(); $(‘#tt’).datagrid(‘reload’, { method: ‘firstLoad’ }); //设置高度 $(“#lineForDataGrid”).find(“.panel”).find(“.datagrid-wrap”).css(“height”, vCenterHeight + “px”); fAddLog(“管理员版MOOC教学”); }) function fLoadTable() { $(‘#tt’).datagrid({ title: ”, url: location.href, pagination: true, pageSize: 20, pagePosition: ‘top’, striped: true, //singleSelect: true, ctrlSelect: true,//在启用多行选择的时候允许使用Ctrl键+鼠标点击的方式进行多选操作。 rownumbers: true, columns: [[ { field: ‘id’, title: ‘id’, align: ‘center’, hidden: true }, { field: ‘name’, title: ‘实训类型’, align: ‘center’ }, { field: ‘remark’, title: ‘备注’, align: ‘center’ }, { field: ‘createDate’, title: ‘新增日期’, align: ‘center’ }, { field: ‘modifyDate’, title: ‘修改日期’, align: ‘center’ }, { field: ‘edit’, title: ‘资源’, align: ‘center’, formatter: fEditResource } ]], toolbar: [{ text: ‘增加’, iconCls: ‘icon-add’, handler: function () { $(‘#dlg’).dialog(‘open’).dialog(‘setTitle’, ‘新增实训信息’); $(‘#dlg_form’).form(‘clear’); vUrl = location.href + ‘?type=add’; } }, { text: ‘修改’, iconCls: ‘icon-edit’, handler: function () { var row = $(‘#tt’).datagrid(‘getSelected’); if (row) { $(‘#dlg’).dialog(‘open’).dialog(‘setTitle’, ‘修改实训信息’); $(‘#dlg_form’).form(‘load’, row); vUrl = location.href + ‘?type=modify&id=’ + row.id; } else { $.messager.alert(‘提示’, ‘请至少选中一项作为修改项.’) } } }, ‘-‘, { text: ‘删除’, iconCls: ‘icon-remove’, handler: function () { var row = $(‘#tt’).datagrid(‘getSelected’); if (row) { $.messager.confirm(‘提示’, ‘您确定要删除这个用户信息吗?’, function (r) { if (r) { vUrl = location.href + ‘?type=del&id=’ + row.id; $.ajax({ type: “POST”, url: vUrl, success: function (json) { var json = eval(‘(‘ + json + ‘)’); if (json.result == true) { $.messager.show({ title: ‘Success’, msg: ‘删除成功!’ }); $(‘#dlg’).dialog(‘close’); // close the dialog $(‘#tt’).datagrid(‘reload’); // reload the user data } else { $.messager.show({ title: ‘Error’, msg: ‘删除失败,请稍后再试!’ }); $(‘#dlg’).dialog(‘close’); // close the dialog $(‘#tt’).datagrid(‘reload’); // reload the user data } } }); } }); } else { $.messager.alert(‘提示’, ‘请至少选中一项作为删除项.’) } } }] }); }; function fSaveData() { $(‘#dlg_form’).form(‘submit’, { url: vUrl, onSubmit: function () { return $(this).form(‘validate’); }, success: function (sjson) { var json = eval(‘(‘ + sjson + ‘)’); if (json.result == true) { $.messager.show({ title: ‘Success’, msg: json.msg ? json.msg : ‘操作成功!’ }); $(‘#dlg’).dialog(‘close’); // close the dialog $(‘#tt’).datagrid(‘reload’); // reload the user data } else { $.messager.show({ title: ‘Error’, msg: json.msg ? json.msg : ‘操作失败,请稍后再试!’ }); $(‘#dlg’).dialog(‘close’); // close the dialog } }, error: function () { $.messager.show({ title: ‘Error’, msg: json.msg ? json.msg : ‘操作失败,请稍后再试!’ }); $(‘#dlg’).dialog(‘close’); // close the dialog } }); } function fEditResource(rowIndex, rowData) { return ‘<a href=”javascript:fOpenResourceManagement(\” + rowData.id + ‘\’,\” + rowData.name + ‘\’)”>管理资源</a>’; } function fOpenResourceManagement(id, name) { $(‘#Resourcedlg’).dialog(‘open’).dialog(‘setTitle’, ‘管理’ + name + ‘资源信息’); vTrainingTypeID = id; } function fLoadResourceTable() { $(‘#ttResource’).datagrid({ title: ”, url: location.href, pagination: true, pageSize: 20, pagePosition: ‘top’, striped: true, //singleSelect: true, ctrlSelect: true,//在启用多行选择的时候允许使用Ctrl键+鼠标点击的方式进行多选操作。 rownumbers: true, columns: [[ { field: ‘id’, title: ‘id’, align: ‘center’, hidden: true }, { field: ‘trainingTypeId’, title: ‘trainingTypeId’, align: ‘center’, hidden: true }, { field: ‘trainingTypeName’, title: ‘实训类型’, align: ‘center’ }, { field: ‘name’, title: ‘资源名称’, align: ‘center’ }, { field: ‘content’, title: ‘资源内容’, align: ‘center’ }, { field: ‘createDate’, title: ‘新增日期’, align: ‘center’ }, { field: ‘modifyDate’, title: ‘修改日期’, align: ‘center’ }, { field: ‘preview’, title: ‘预览’, align: ‘center’, formatter: fEditResource } ]], toolbar: [{ text: ‘增加’, iconCls: ‘icon-add’, handler: function () { $(‘#dlgForResource’).dialog(‘open’).dialog(‘setTitle’, ‘新增资源信息’); $(‘#trainingTypeId’).combobox(‘reload’, ‘MOOCEducationManagement.aspx?type=loadTrainingType’); $(‘#dlg_formForResource’).form(‘clear’); $(‘#trainingTypeId’).combobox(‘select’, vTrainingTypeID); vUrl = location.href + ‘?type=addResource’; } }, { text: ‘修改’, iconCls: ‘icon-edit’, handler: function () { var row = $(‘#ttResourcet’).datagrid(‘getSelected’); if (row) { $(‘#dlgForResource’).dialog(‘open’).dialog(‘setTitle’, ‘修改资源信息’); $(‘#trainingTypeId’).combobox(‘reload’, ‘MOOCEducationManagement.aspx?type=loadTrainingType’); $(‘#dlg_formForResource’).form(‘load’, row); vUrl = location.href + ‘?type=modifyResource&id=’ + row.id; } else { $.messager.alert(‘提示’, ‘请至少选中一项作为修改项.’) } } }, ‘-‘, { text: ‘删除’, iconCls: ‘icon-remove’, handler: function () { var row = $(‘#ttResource’).datagrid(‘getSelected’); if (row) { $.messager.confirm(‘提示’, ‘您确定要删除这个资源信息吗?’, function (r) { if (r) { vUrl = location.href + ‘?type=delResource&id=’ + row.id; $.ajax({ type: “POST”, url: vUrl, success: function (json) { var json = eval(‘(‘ + json + ‘)’); if (json.result == true) { $.messager.show({ title: ‘Success’, msg: ‘删除成功!’ }); $(‘#dlgForResource’).dialog(‘close’); // close the dialog $(‘#ttResource’).datagrid(‘reload’); // reload the user data } else { $.messager.show({ title: ‘Error’, msg: ‘删除失败,请稍后再试!’ }); $(‘#dlgForResource’).dialog(‘close’); // close the dialog $(‘#ttResource’).datagrid(‘reload’); // reload the user data } } }); } }); } else { $.messager.alert(‘提示’, ‘请至少选中一项作为删除项.’) } } }] }); }; function fSaveResourceData() { var vStatus = $(“#dlg_formForResource”).form(‘validate’); if (vStatus) { var formData = new FormData($(“#dlg_formForResource”)[0]); $.ajax({ url: vUrl, type: ‘POST’, data: formData, async: false, cache: false, contentType: false, processData: false, // dataType: “jsonp”,//问题就在这里,如果用了jsonp,那么后台就接收不到文件流,无法获得文件流,就没办法把文件写入服务器。如果不指定,就是注释掉,虽然ajax提交之后,还是跑到error那里去,但是文件已经是成功写入服务器的了。 jsonp: “jsoncallback”, success: function (returndata) { var json = eval(‘(‘ + returndata + ‘)’); if (json.result == true) { $.messager.show({ title: ‘Success’, msg: json.msg ? json.msg : ‘操作成功!’ }); $(‘#dlgForResource’).dialog(‘close’); // close the dialog $(‘#ttResource’).datagrid(‘reload’); // reload the user data } else { $.messager.show({ title: ‘Error’, msg: json.msg ? json.msg : ‘操作失败,请稍后再试!’ }); $(‘#dlgForResource’).dialog(‘close’); // close the dialog } }, error: function (returndata) { var json = eval(‘(‘ + returndata + ‘)’); $.messager.show({ title: ‘Error’, msg: json.msg ? json.msg : ‘操作失败,请稍后再试!’ }); $(‘#dlgForResource’).dialog(‘close’); // close the dialog } }); } else { return $(“#dlg_formForResource”).form(‘validate’); } //$(‘#dlg_formForResource’).form(‘submit’, { // url: vUrl, // onSubmit: function () { // return $(this).form(‘validate’); // }, // success: function (sjson) { // var json = eval(‘(‘ + sjson + ‘)’); // if (json.result == true) { // $.messager.show({ // title: ‘Success’, // msg: json.msg ? json.msg : ‘操作成功!’ // }); // $(‘#dlgForResource’).dialog(‘close’); // close the dialog // $(‘#ttResource’).datagrid(‘reload’); // reload the user data // } else { // $.messager.show({ // title: ‘Error’, // msg: json.msg ? json.msg : ‘操作失败,请稍后再试!’ // }); // $(‘#dlgForResource’).dialog(‘close’); // close the dialog // } // }, // error: function () { // $.messager.show({ // title: ‘Error’, // msg: json.msg ? json.msg : ‘操作失败,请稍后再试!’ // }); // $(‘#dlgForResource’).dialog(‘close’); // close the dialog // } //}); } </script></body></html>
后台代码:using LmxPublic;using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;namespace Web.Admin{ public partial class MOOCEducationManagement : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { if (Request.Form[“method”] == “firstLoad”) { List<trainingtype> list = dataLoader.getTrainingTypeList(); int page = string.IsNullOrWhiteSpace(Request[“page”]) ? 1 : Int32.Parse(Request[“page”]); int rows = string.IsNullOrWhiteSpace(Request[“rows”]) ? 1 : Int32.Parse(Request[“rows”]); string order = string.IsNullOrWhiteSpace(Request[“order”]) ? “desc” : Request[“order”].ToUpper(); string sort = string.IsNullOrWhiteSpace(Request[“sort”]) ? “id” : Request[“sort”]; IQueryable<trainingtype> query = CommonTools.DataSorting<trainingtype>(list.AsQueryable(), sort, order).Skip((page – 1) * rows).Take(rows); Response.Write(JsonHelper.Serialize(new { total = list.Count, rows = query })); Response.End(); } if (Request.QueryString[“type”] == “add”) { string strMsg; if (AddObject(out strMsg)) { Response.Write(JsonHelper.Serialize(new { result = true, msg = strMsg })); } else { Response.Write(JsonHelper.Serialize(new { result = false, msg = strMsg })); } Response.End(); } if (Request.QueryString[“type”] == “modify”) { string strMsg; if (ModifyObject(out strMsg)) { Response.Write(JsonHelper.Serialize(new { result = true, msg = strMsg })); } else { Response.Write(JsonHelper.Serialize(new { result = false, msg = strMsg })); } Response.End(); } if (Request.QueryString[“type”] == “del”) { string strMsg; if (DelObject(out strMsg)) { Response.Write(JsonHelper.Serialize(new { result = true, msg = strMsg })); } else { Response.Write(JsonHelper.Serialize(new { result = false, msg = strMsg })); } Response.End(); } if (Request.QueryString[“type”] == “addResource”) { string strMsg; if (AddResourceObject(out strMsg)) { Response.Write(JsonHelper.Serialize(new { result = true, msg = strMsg })); } else { Response.Write(JsonHelper.Serialize(new { result = false, msg = strMsg })); } Response.End(); } if (Request.QueryString[“type”] == “modifyResource”) { string strMsg; if (ModifyResourceObject(out strMsg)) { Response.Write(JsonHelper.Serialize(new { result = true, msg = strMsg })); } else { Response.Write(JsonHelper.Serialize(new { result = false, msg = strMsg })); } Response.End(); } if (Request.QueryString[“type”] == “delResource”) { string strMsg; if (DelResourceObject(out strMsg)) { Response.Write(JsonHelper.Serialize(new { result = true, msg = strMsg })); } else { Response.Write(JsonHelper.Serialize(new { result = false, msg = strMsg })); } Response.End(); } if (Request.QueryString[“type”] == “loadTrainingType”) { List<trainingtype> list = dataLoader.getTrainingTypeList(); string strJson = JsonHelper.Serialize(list); Response.Write(strJson); Response.End(); } if (Session[“systemUser”] != null) { systemuser aUser = (systemuser)(Session[“systemUser”]); if (aUser != null) { lbUserName.Text = aUser.name; } else { Response.Redirect(“/index.aspx”); } } else { Response.Redirect(“/index.aspx”); } } } /// <summary> /// 增加一个对一个对象. /// </summary> /// <returns></returns> private bool AddObject(out string strMsg) { string name = Request.Form[“name”]; string remark = Request.Form[“remark”]; bool bPass = false; try { using (trainingsystemEntities ent = new trainingsystemEntities()) { trainingtype aNewModel = new trainingtype() { createDate = DateTime.Now, isDelete = false, modifyDate = DateTime.Now, name = name, remark = remark }; ent.trainingtype.Add(aNewModel); if (ent.SaveChanges() > 0) { bPass = true; strMsg = “增加成功。”; } else { bPass = false; strMsg = “增加失败,请稍后再试。”; } } } catch (Exception ex) { strMsg = ex.Message; bPass = false; } return bPass; } /// <summary> /// 更新一个对象. /// </summary> /// <returns></returns> private bool ModifyObject(out string strMsg) { string id = Request.QueryString[“id”]; string name = Request.Form[“name”]; string remark = Request.Form[“remark”]; int iId = DataFormat.ConvertDBNullToInt32(id); bool bPass = false; try { using (trainingsystemEntities ent = new trainingsystemEntities()) { trainingtype aModel = (from c in ent.trainingtype where c.id == iId && c.isDelete != true select c).FirstOrDefault(); if (aModel != null) { aModel.modifyDate = DateTime.Now; aModel.name = name; aModel.remark = remark; if (ent.SaveChanges() > 0) { bPass = true; strMsg = “修改成功。”; } else { bPass = false; strMsg = “修改失败,请稍后再试。”; } } else { bPass = false; strMsg = “不存在此记录,请稍后再试。”; } } } catch (Exception ex) { strMsg = ex.Message; bPass = false; //throw; } return bPass; } /// <summary> /// 删除一个对象. /// </summary> /// <returns></returns> private bool DelObject(out string strMsg) { string id = Request.QueryString[“id”]; int iID = DataFormat.ConvertDBNullToInt32(id); bool bPass = false; using (trainingsystemEntities ent = new trainingsystemEntities()) { trainingtype aModel = (from c in ent.trainingtype where c.id == iID && c.isDelete == false select c).FirstOrDefault(); try { if (aModel != null) { aModel.isDelete = true; if (ent.SaveChanges() > 0) { bPass = true; strMsg = “删除成功。”; } else { bPass = false; strMsg = “删除失败,请稍后再试。”; } } else { bPass = false; strMsg = “不存在此记录,请稍后再试。”; } } catch (Exception ex) { bPass = false; strMsg = ex.Message; } } return bPass; } /// <summary> /// 增加一个对一个对象. /// </summary> /// <returns></returns> private bool AddResourceObject(out string strMsg) { string trainingTypeId = Request.Form[“trainingTypeId”]; string trainingName = Request.Form[“trainingName”]; string pic = Request.Form[“pic”]; //pic = pic.Substring(pic.LastIndexOf(“/fakepath”) + 9);// 取出文件名的路径(不包括文件的名称) string content = Request.Form[“content”]; int iTrainingTypeID = DataFormat.ConvertDBNullToInt32(trainingTypeId); HttpFileCollection files = HttpContext.Current.Request.Files; byte[] b = new byte[files[0].ContentLength]; System.IO.Stream fs = (System.IO.Stream)files[0].InputStream; fs.Read(b, 0, files[0].ContentLength); ///定义并实例化一个内存流,以存放提交上来的字节数组。 MemoryStream m = new MemoryStream(b); ///定义实际文件对象,保存上载的文件。 FileStream f = new FileStream(Server.MapPath(“\\Admin\\attached”) + “\\” + files[0].FileName, FileMode.Create); ///把内内存里的数据写入物理文件 m.WriteTo(f); m.Close(); f.Close(); f = null; m = null; pic = files[0].FileName; bool bPass = false; try { using (trainingsystemEntities ent = new trainingsystemEntities()) { trainingresource aNewModel = new trainingresource() { content = content, createDate = DateTime.Now, isDelete = false, modifyDate = DateTime.Now, name = trainingName, pic = pic, trainingTypeId = iTrainingTypeID }; ent.trainingresource.Add(aNewModel); ent.Configuration.ValidateOnSaveEnabled = false;//关闭验证 if (ent.SaveChanges() > 0) { ent.Configuration.ValidateOnSaveEnabled = true;//关闭验证 bPass = true; strMsg = “增加成功。”; } else { bPass = false; strMsg = “增加失败,请稍后再试。”; } } } catch (Exception ex) { strMsg = ex.Message; bPass = false; } return bPass; } /// <summary> /// 更新一个对象. /// </summary> /// <returns></returns> private bool ModifyResourceObject(out string strMsg) { string id = Request.QueryString[“id”]; string trainingTypeId = Request.Form[“trainingTypeId”]; string trainingName = Request.Form[“trainingName”]; string pic = Request.Form[“pic”]; string content = Request.Form[“content”]; int iTrainingTypeID = DataFormat.ConvertDBNullToInt32(trainingTypeId); int iId = DataFormat.ConvertDBNullToInt32(id); bool bPass = false; try { using (trainingsystemEntities ent = new trainingsystemEntities()) { trainingresource aModel = (from c in ent.trainingresource where c.id == iId && c.isDelete != true select c).FirstOrDefault(); if (aModel != null) { aModel.modifyDate = DateTime.Now; aModel.trainingTypeId = iTrainingTypeID; aModel.content = content; aModel.name = trainingName; aModel.pic = pic; if (ent.SaveChanges() > 0) { bPass = true; strMsg = “修改成功。”; } else { bPass = false; strMsg = “修改失败,请稍后再试。”; } } else { bPass = false; strMsg = “不存在此记录,请稍后再试。”; } } } catch (Exception ex) { strMsg = ex.Message; bPass = false; //throw; } return bPass; } /// <summary> /// 删除一个对象. /// </summary> /// <returns></returns> private bool DelResourceObject(out string strMsg) { string id = Request.QueryString[“id”]; int iID = DataFormat.ConvertDBNullToInt32(id); bool bPass = false; using (trainingsystemEntities ent = new trainingsystemEntities()) { trainingtype aModel = (from c in ent.trainingtype where c.id == iID && c.isDelete == false select c).FirstOrDefault(); try { if (aModel != null) { aModel.isDelete = true; if (ent.SaveChanges() > 0) { bPass = true; strMsg = “删除成功。”; } else { bPass = false; strMsg = “删除失败,请稍后再试。”; } } else { bPass = false; strMsg = “不存在此记录,请稍后再试。”; } } catch (Exception ex) { bPass = false; strMsg = ex.Message; } } return bPass; } protected void btnSubmit_Click(object sender, EventArgs e) { string strMsg=””; AddResourceObject(out strMsg); } }
}