这次我是在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.com
QQ: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);
        }
    }

}  




附件列表

Ajax 提交KindEditor的数据的更多相关文章

  1. spring mvc接收ajax提交的JSON数据,并反序列化为对象

    需求:spring mvc接收ajax提交的JSON数据,并反序列化为对象,代码如下: 前台JS代码: //属性要与带转化的对象属性对应 var param={name:'语文',price:16}; ...

  2. 使用ajax提交的json数据,产生筹码问题

    使用ajax提交的json数据,我们必须添加produces注解,如下所示.否则将会产生乱码 方法一:添加produces注解 @ApiOperation(value = "删除日志&quo ...

  3. 使用@RequestBody注解获取Ajax提交的json数据

    最近在学习有关springMVC的知识,今天学习如何使用@RequestBody注解来获取Ajax提交的json数据内容. Ajax部分代码如下: 1 $(function(){ 2 $(" ...

  4. ajax提交含有html数据时的处理方法

    这两天在做一个文章内修改的功能,由于前端选用的Extjs控件库,于是就使用Ext.form.HtmlEditor. 在使用ajax提交数据的时候,需要提交包含有html代码的数据.这时候问题就来了,不 ...

  5. jquery序列化from表单使用ajax提交返回json数据(使用struts2注解result type = json)

    1.action类引入struts2的"json-default"拦截器栈 @ParentPackage("json-default") //示例 @Paren ...

  6. ajax 提交 json格式数据到后台

    例子:$.ajax({ type: 'POST', url: "/ROOT/modify.do", contentType: "application/json" ...

  7. 关于上传文件 非ajax提交 得到后台数据问题

    <form name="configForm" id="configForm" method="post" action=" ...

  8. ajax提交复杂对象数据

    public class RouteItemManageReq { private List<WorkNodeReq> targetNodes; private RouteItemReq ...

  9. jquery Ajax提交表单数据

    //表单中控件的name要和实体类字段属性一致 $.ajax({ cache: true, type: "POST", url:ajaxCallUrl, data:$('#your ...

随机推荐

  1. Python编码记录

    字节流和字符串 当使用Python定义一个字符串时,实际会存储一个字节串: "abc"--[97][98][99] python2.x默认会把所有的字符串当做ASCII码来对待,但 ...

  2. 如何一步一步用DDD设计一个电商网站(五)—— 停下脚步,重新出发

    阅读目录 前言 单元测试 纠正错误,重新出发 结语 一.前言 实际编码已经写了2篇了,在这过程中非常感谢有听到观点不同的声音,借着这个契机,今天这篇就把大家提出的建议一个个的过一遍,重新整理,重新出发 ...

  3. 如何一步一步用DDD设计一个电商网站(二)—— 项目架构

    阅读目录 前言 六边形架构 终于开始建项目了 DDD中的3个臭皮匠 CQRS(Command Query Responsibility Segregation) 结语 一.前言 上一篇我们讲了DDD的 ...

  4. 【Win 10 应用开发】在App所在的进程中执行后台任务

    在以往版本中,后台任务都是以独立的专用进程来运行,因此,定义后台任务代码的类型都要位于 Windows 运行时组件项目中. 不过,在14393中,SDK 作了相应的扩展,不仅支持以前的独立进程中运行后 ...

  5. 玩转spring boot——MVC应用

    如何快速搭建一个MCV程序? 参照spring官方例子:https://spring.io/guides/gs/serving-web-content/ 一.spring mvc结合thymeleaf ...

  6. scanf类型不匹配造成死循环

        int i = 0; while (flag) { printf("please input a number >>> "); scanf("% ...

  7. 设计模式C#合集--工厂方法模式

    简单工厂,代码: public interface ISpeak { public void Say(); } public class Hello : ISpeak { public void Sa ...

  8. Android的Kotlin秘方(I):OnGlobalLayoutListener

    春节后,又重新“开张”.各位高手请继续支持.谢谢! 原文标题:Kotlin recipes for Android (I): OnGlobalLayoutListener 原文链接:http://an ...

  9. 关于Genymotion下载比较慢的解决办法

    Genymotion号称Android模拟器中运行最快的,但是服务器在国外,Android镜像下载起来那个速度就不想说了. Add new device后下载速度太慢了,容易失败 先登录,然后add, ...

  10. Linux基础介绍【第一篇】

    Linux简介 什么是操作系统? 操作系统,英文名称Operating System,简称OS,是计算机系统中必不可少的基础系统软件,它是应用程序运行以及用户操作必备的基础环境支撑,是计算机系统的核心 ...