当前位置:   article > 正文

C#结合JS实现HtmlTable动态添加行并保存到数据库_html点击添加表格添加一行数据,并保存中数据

html点击添加表格添加一行数据,并保存中数据

   

目录

需求

效果视频演示

范例运行环境

准备数据源

数据表设计

UI及表结构Json配置

Json数据包提交配置

设计实现

前端UI

Javascript 脚本

Jquery引用

C# 服务端操作 

小结


需求

在 Web 应用项目中,实现一对多录入的数据管理功能是一项常见的应用。因此可以实现一个相对轻量化的设计实现表格的录入,为保证功能的可用性、界面友好性,总体的需求如下:

1、数据网格可以动态的添加行,行可以提供输入框、选择框的控件进行录入。

2、数据网格可以删除选中的行。

3、数据网格可以上下移动选中的行重新进行排序。

4、可以实现数据的有效性验证功能(如必填写、位数限制、类型限制等)。

5、需要对输入的文字过滤和屏蔽HTML标记等危险内容。

6、添加新行前判断已有行的有效性,对于未校验通过的暂不允许添加新行。

7、对于修改中的、保存时的、保存后的状态有一定的相关提示信息。

8、数据保存实现动态无刷新。

效果视频演示

为实现需求会使用到用C# 编写服务端Web 静态方法,Jquery 实现 Ajax 无刷新技术并调用服务器方法,Json 存储数据表格需要的配置,客户端大部分设计使用 Javascript 实现。实现的效果演示视频如下:

动态添加 HtmlTable 行并保存到数据库

范例运行环境

操作系统: Windows Server 2019 DataCenter

数据库:Microsoft SQL Server 2016

.net版本: .netFramework4.0 或以上

开发工具及相关技术:VS2019  C# 、Jquery 、Json、Javascript

准备数据源

数据表设计

我们在 MS SQL Server 创建 att_jypx(教育培训经历表),其结构如下表:

序号字段名类型说明
1ciduniqueidentifier行唯一标识,唯一键
2xmbhvarchar(20)外键父项,指项目编号
3sfzhnvarchar(18)外键父项,指身份证号
4nf1nvarchar(4)起始年份
5yf1nvarchar(2)起始月份
6nf2nvarchar(4)截止年份
7yf2nvarchar(2)截止月份
8xxmcnvarchar(100)学校名称
9zynvarchar(50)所学专业
10xlnvarchar(10)学历
11byzlbnvarchar(50)毕业证类别
12xhint排序号

执行如下 创建表的 SQL 语句:

  1. CREATE TABLE [dbo].[att_jypx](
  2. [cid] [uniqueidentifier] ROWGUIDCOL NOT NULL,
  3. [xmbh] [varchar](20) NOT NULL,
  4. [sfzh] [nvarchar](18) NOT NULL,
  5. [nf1] [nvarchar](4) NULL,
  6. [yf1] [nvarchar](2) NULL,
  7. [nf2] [nvarchar](4) NULL,
  8. [yf2] [nvarchar](2) NULL,
  9. [xxmc] [nvarchar](100) NULL,
  10. [zy] [nvarchar](50) NULL,
  11. [xl] [nvarchar](10) NULL,
  12. [byzlb] [nvarchar](50) NULL,
  13. [xh] [int] NULL,
  14. CONSTRAINT [PK_att_jypx] PRIMARY KEY CLUSTERED
  15. (
  16. [cid] ASC
  17. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  18. ) ON [PRIMARY]
  19. GO
  20. ALTER TABLE [dbo].[att_jypx] ADD CONSTRAINT [DF_att_jypx_cid] DEFAULT (newid()) FOR [cid]
  21. GO

数据表的其它说明如下:

1、CID字段为GUID类型,可用于标识 HtmlTable 的 Row 行对象的 ID 并用于存储。

2、xmbh 字段和 sfzh 字段是引用的外键,我们为了演示方便假设为 项目编号 为‘001’、身份证号为‘120102’

3、xh 为排序记录顺序所用。

以上的所述字段均不参与 HtmlTable 表格内容的呈现,以降低数据包的容量,只参与外键操作。

UI及表结构Json配置

对于 HtmlTable 表格内容的呈现、数据结构及数据验证的校验,我们将使用Json文件进行配置,配置说明如下:

序号类型说明
1maxRowCount字符允许添加的最大行数
2mtable_style字符主体编辑HtmlTable的风格
3ttable_style字符标题HtmlTable的风格
4cols数组列数组定义变量,以下5到12均为 cols 所包含每一数组元素对象的属性
5fname字符字段名
6cname字符字段中文名或说明
7 len数字字段长度
8td_style字符HtmlTabelCell 单元格的风格
9ctl_style字符单元格中输入或选择控件的风格
10 input字符可输入 text 和 select,分别对应输入框和选择框
11 list字符用于select选择框的选项设置,各选项间以 “|” 进行分隔
12 check字符用于数据校验方案设置,如果设置请参考我的文章《C# 结合 JavaScript 对 Web 控件进行数据输入验证》

 完全的样例JSON如下:

 

  1. {
  2. "att_jypx":[
  3. {"maxRowCount":12,
  4. "mtable_style":"table-layout: fixed;word-break: break-all; word-wrap: break-word;font-size:10pt; width:700px; position:absolute;left:0px; border-color:rgb(235,235,235); border-width:1px 1px 1px 1px;border-collapse:collapse;",
  5. "ttable_style":"z-index:9999;position:fixed;left:0px;top:37px;table-layout: fixed;word-break: break-all; word-wrap: break-word;font-size:10pt; width:700px; background-color:rgb(235,235,235);border-color:rgb(235,235,235); border-width:1px 1px 1px 1px;border-collapse:collapse;",
  6. "cols": [
  7. {
  8. "fname": "nf1",
  9. "cname": "起始年份",
  10. "len":4,
  11. "td_style":"width:75px",
  12. "ctl_style":"width:70px;border-radius:2px;border-width:1px;",
  13. "input":"text",
  14. "list":"",
  15. "display":"",
  16. "check":"notnull|mustlen4|int"
  17. },
  18. {
  19. "fname": "yf1",
  20. "cname": "起始月份",
  21. "len":2,
  22. "td_style":"width:75px",
  23. "ctl_style":"width:70px;border-radius:2px;",
  24. "input":"select",
  25. "list":"01|02|03|04|05|06|07|08|09|10|11|12",
  26. "check":"notnull"
  27. },
  28. {
  29. "fname": "nf2",
  30. "cname": "截止年份",
  31. "len":4,
  32. "td_style":"width:75px",
  33. "ctl_style":"width:70px;border-radius:2px;border-width:1px;",
  34. "input":"text",
  35. "list":"",
  36. "display":"",
  37. "check":"notnull|mustlen4|int"
  38. },
  39. {
  40. "fname": "yf2",
  41. "cname": "截止月份",
  42. "len":2,
  43. "td_style":"width:75px",
  44. "ctl_style":"width:70px;border-radius:2px;",
  45. "input":"select",
  46. "list":"01|02|03|04|05|06|07|08|09|10|11|12",
  47. "check":"notnull"
  48. },
  49. {
  50. "fname": "xxmc",
  51. "cname": "所在院校",
  52. "len":100,
  53. "td_style":"width:200px;",
  54. "ctl_style":"width:195px;border-radius:2px;border-width:1px;",
  55. "input":"text",
  56. "list":"",
  57. "check":"notnull|maxlen100"
  58. },
  59. {
  60. "fname": "xl",
  61. "cname": "学历",
  62. "len":10,
  63. "td_style":"width:60px",
  64. "ctl_style":"width:55px;border-radius:2px;border-width:1px;",
  65. "input":"text",
  66. "list":"",
  67. "check":"notnull|maxlen10"
  68. },
  69. {
  70. "fname": "zy",
  71. "cname": "所学专业",
  72. "len":50,
  73. "td_style":"width:80px",
  74. "ctl_style":"width:75px;border-radius:2px;border-width:1px;",
  75. "input":"text",
  76. "list":"",
  77. "check":"notnull|maxlen50"
  78. },
  79. {
  80. "fname": "byzlb",
  81. "cname": "毕业证类别",
  82. "len":50,
  83. "td_style":"width:160px",
  84. "ctl_style":"width:155px;border-radius:2px;border-width:1px;",
  85. "input":"select",
  86. "list":"全日制普通高等教育毕业证|成人高等教育毕业证|高等教育自学考试毕业证|其他",
  87. "check":"notnull"
  88. } ]
  89. }
  90. ]
  91. }

Json数据包提交配置

Json数据包根据Json配置信息通过服务端生成,主要包括字段名的项,用于将来提交数据时使用,因为提交的数据方式仍然是Json数据对象,即Json数据包,生成的初始格式如下示例:

  1. {"nf1":"",
  2. "yf1":"",
  3. "nf2":"",
  4. "yf2":"",
  5. "xxmc":"",
  6. "zy":"",
  7. "xmbh":"001",
  8. "sfzh":"120102",
  9. "xh":"",
  10. "cid":"",
  11. "com_name":"jypx"}

设计实现

前端UI

前端UI我们主要放置一些中间变量控件,表格元素等,主要元素说明见下表:

序号元素Id类型说明
1curidTextBox用于记录当前点行的ID
2pjsonTextBox用于存储Json配置数据
3djsonTextBox用于存储Json提交数据包
4ttableHtmlTable标题列表格,用于固定显示表头
5mtableHtmlTable主编辑表格对象
6topnavsDiv一组固定于顶端的工具栏对象层,包括新增、删除、上移、下移、保存按钮

示例代码如下:

  1. <form runat="server">
  2. <asp:TextBox ID="cid" style="display:none" runat="server"></asp:TextBox>
  3. <asp:TextBox ID="com_name" style="display:none" runat="server"></asp:TextBox>
  4. <asp:TextBox ID="xmbh" style="display:none" runat="server"></asp:TextBox>
  5. <asp:TextBox ID="sfzh" style="display:none" runat="server"></asp:TextBox>
  6. <asp:TextBox ID="p_acode" Runat="server" Visible="true" style="display:none" ></asp:TextBox>
  7. <asp:TextBox ID="curid" Runat="server" Visible="true" style="display:none" ></asp:TextBox>
  8. <asp:TextBox ID="pjson" TextMode="MultiLine" Runat="server" Visible="true" style="display:none" ></asp:TextBox>
  9. <asp:TextBox ID="djson" TextMode="MultiLine" Runat="server" Visible="true" style="display:none" ></asp:TextBox>
  10. <div id="topnavs" runat="server" style=" z-index:9999; border-bottom: 1px solid silver; padding:3px;display:flex;justify-content:start; background-color:rgb(235,235,235); position:fixed;top:0px;left:0px;width:100%;height:30px; text-align:center; line-height:30px;">
  11. <input id="closebutton" runat="server" type="button" value='' style=" border-width:0px; background-position:center; background-image:url(/images/att_add6.jpg);font-size:14pt;cursor:pointer;width:25px;height:25px;" onclick="addRow()" class="" />
  12. <input id="Button1" runat="server" type="button" value='' style=" border-width:0px;background-position:center; background-image:url(/images/att_del.jpg); margin-left:5px; font-size:14pt;cursor:pointer;width:25px;height:25px;" onclick='delinfo()' class="" />
  13. <input id="Button2" runat="server" type="button" value='' style="border-width:0px; background-position:center; background-image:url(/images/att_up2.jpg); margin-left:5px; font-size:14pt;cursor:pointer;width:25px;height:25px;" onclick="swarp(document.getElementById('curid').value,1);" class="" />
  14. <input id="Button3" runat="server" type="button" value='' style="border-width:0px; background-position:center; background-image:url(/images/att_down3.jpg); margin-left:5px; font-size:14pt;cursor:pointer;width:25px;height:25px;" onclick="swarp(document.getElementById('curid').value,2);" class="" />
  15. <input id="Button4" runat="server" type="button" value='' style="border-width:0px; background-position:center; background-image:url(/images/att_save.jpg); margin-left:5px; font-size:14pt;cursor:pointer;width:25px;height:25px;" onclick="if (validall('') == false) {document.getElementById('Button4').removeAttribute('disabled');return;}saveall();if(document.getElementById('mtable').rows.length>0){ this.setAttribute('disabled','true');}" class="" />
  16. <div id="saved" style="margin-left:10px; font-weight:bold; font-size:11pt; color:Red; "></div>
  17. </div>
  18. <table align="left" id="ttable" runat="server" style="z-index:9999;position:fixed;left:0px;top:37px;table-layout: fixed;word-break: break-all; word-wrap: break-word;font-size:10pt; width:700px; background-color:rgb(235,235,235);border-color:rgb(235,235,235); border-width:1px 1px 1px 1px;border-collapse:collapse;" border="1" cellspacing="0" cellpadding="3">
  19. </table>
  20. <table align="left" id="mtable" runat="server" style="table-layout: fixed;word-break: break-all; word-wrap: break-word;font-size:10pt; width:700px; position:absolute;left:0px;top:67px; border-color:rgb(235,235,235); border-width:1px 1px 1px 1px;border-collapse:collapse;" border="1" cellspacing="0" cellpadding="3">
  21. </table>
  22. </form>

Javascript 脚本

Javascript 脚本实现表格编辑操作及通过Ajax与服务器方法通信,并保存数据的功能,主要方法说明见下表:

序号方法名称参数说明
1simplecheck

chkobj:单元格对象

_chkvalue:单元格编辑的值

 allowAlert:是否允许弹出提示

etip:弹出提示的扩展前缀字串

本方法用于数据有效性的校验

2swarp

mId:当前行的ID

stype:移动方向,1上移,2下移

用于对选中行的移动排序操作
3chnRowSelColorrowobj:当前行对象用于高亮显示选中行的颜色,并同时将当前行设置为可编辑状态
4tojsonstrstr:输入的值对输入的值进行安全检测,并移除HTML标记,对单引号双引号做特殊处理,以保证JSON字符串传递的字符合法性
5saveall保存所有行记录并提交数据库操作
6delinfo删除当前选中的行并提交数据库操作
7validallextip:附加的前缀性提示保存前对所有行进行数据有效性校验
8validchangeobj:当前编辑的控件元素提示用户当前正修改哪个控件元素的值
9validsaveextip:附加的前缀性提示用于检验是否正有保存的记录
10addRow添加一个新行并提交到数据库操作
11gGuid用于增加新行时生成一个GUID字符串
12ScrollToBottom用于增加新行时自动滚动到页面底部

完整示例代码如下:

  1. <script language="javascript">
  2. function simplecheck(chkobj, _chkvalue, allowAlert,etip) {
  3. check_result = true; check_errid = ''; check_errmsg = '';var _checkSchema = chkobj.getAttribute('checkSchema');var _cName = chkobj.getAttribute('cName');
  4. if (_checkSchema.indexOf('ctrim') != -1) { _chkvalue = ctrim(_chkvalue); } var _objlength = _chkvalue.length; if (_checkSchema.indexOf('abslen') != -1) { _objlength = PositionLen(_chkvalue); }
  5. var _schemaList = _checkSchema.split('|'); var _reqeustnotnull = false;
  6. for (var k = 0; k < _schemaList.length; k++) { if (_schemaList[k].toLowerCase() == 'notnull') { _reqeustnotnull = true; } }
  7. if ((!_reqeustnotnull) && (_chkvalue == '')) { return check_result; }
  8. for (var j = 0; j < _schemaList.length; j++) {
  9. var curSchema = _schemaList[j].toLowerCase(); check_errid = curSchema; var curErrmsg = ''; switch (true) { case curSchema == 'notnull': check_result = isNotNull(_chkvalue); curErrmsg = _cName + '需要填写内容!'; break; case curSchema == 'number': check_result = isNumber(_chkvalue); curErrmsg = _cName + ' 输入的数值不合理,请核对!'; break; case curSchema == 'bnumber': check_result = isBNumber(_chkvalue); curErrmsg = _cName + ' 输入的数值应为>=0的正数,请核对!'; break; case curSchema == 'snumber': check_result = isSNumber(_chkvalue); curErrmsg = _cName + ' 输入的数值应为<0的负数,请核对!'; break; case curSchema == 'date': check_result = isDate(_chkvalue, _cName); check_errid = 'date'; check_errmsg = (check_result ? '' : _cName + ' 输入的日期不合理,请核对!'); curErrmsg = ''; break; case curSchema.indexOf('minlen') != -1: var _slen = parseInt(curSchema.substr('minlen'.length, curSchema.length - 'minlen'.length), 10); if (isNaN(_slen)) { check_result = false; curErrmsg = _cName + ' 输入的最小位数参数不合理,请与软件供应商联系!'; } else { check_result = (_objlength < _slen ? false : true); curErrmsg = _cName + ' 的内容要求最小输入' + _slen + '位,请核对!'; } break; case curSchema.indexOf('maxlen') != -1: var _slen = parseInt(curSchema.substr('maxlen'.length, curSchema.length - 'maxlen'.length), 10); if (isNaN(_slen)) { check_result = false; curErrmsg = _cName + ' 输入的最大位数参数不合理,请与软件供应商联系!'; } else { check_result = (_objlength > _slen ? false : true); curErrmsg = _cName + ' 最大允许输入' + _slen + '位,请核对!'; } break; case curSchema.indexOf('mustlen') != -1: var _slen = parseInt(curSchema.substr('mustlen'.length, curSchema.length - 'mustlen'.length), 10); if (isNaN(_slen)) { check_result = false; curErrmsg = _cName + ' 输入的限制位数参数不合理,请与软件供应商联系!'; } else { check_result = (_objlength != _slen ? false : true); curErrmsg = _cName + ' 的内容输入长度只能是' + _slen + '位,请核对!'; } break; case curSchema == 'time': check_result = validRegs(_chkvalue, /^\d{1,2}:\d{1,2}:\d{1,2}$/); curErrmsg = _cName + ' 输入的时间不合理,请核对。'; break; case curSchema == 'alpha': check_result = isAlpha(_chkvalue); curErrmsg = _cName + ' 只能输入的数字、字母和下划线,请核对。'; break; case curSchema == 'mail': check_result = validRegs(_chkvalue, /^([a-zA-Z0-9._-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/); curErrmsg = _cName + ' 输入的邮件地址不合理,请核对。'; break; case curSchema == 'phone': check_result = validRegs(_chkvalue, /([a-zA-Z0-9\.-\u4e00-\u9fa5]{8,})$/); curErrmsg = _cName + ' 输入的电话号码不合理,请核对。'; break; case curSchema == 'mobile': check_result = validRegs(_chkvalue, /^1(3[0-9]|5[012356789]|8[056789])\d{8}$/); curErrmsg = _cName + ' 输入的手机号码不合理,请核对。'; break; case curSchema == 'money': check_result = validRegs(_chkvalue, /^\d+(\.\d+)?$/); curErrmsg = _cName + ' 输入的内容不符合货币类型的要求,请核对。'; break; case curSchema == 'zip': check_result = validRegs(_chkvalue, /^[1-9]\d{5}$/); curErrmsg = _cName + ' 输入的邮政编码不合理,请核对。'; break; case curSchema == 'int': check_result = validRegs(_chkvalue, /^[-\+]?\d+$/); curErrmsg = _cName + ' 需要输入一个整数,请核对。'; break; case curSchema == 'en': check_result = validRegs(_chkvalue, /^[A-Za-z]+$/); curErrmsg = _cName + ' 只能输入英文大小写字母,请核对。'; break; case curSchema == 'cn': check_result = validRegs(_chkvalue, /^[\u0391-\uFFE5]+$/); curErrmsg = _cName + ' 只能输入中文,请核对。'; break; case curSchema == 'url': check_result = validRegs(_chkvalue, /([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/); curErrmsg = _cName + ' 输入的网址不合理,请核对。'; break; case curSchema == 'idcard18': rv_result = checkIdcard(_chkvalue); check_result = (rv_result == '' ? true : false); curErrmsg = _cName + rv_result; break; case curSchema == 'idcard15': rv_result = checkIdcard(_chkvalue); check_result = (rv_result == '' ? true : false); curErrmsg = _cName + rv_result; break; case curSchema == 'idcard': rv_result = checkIdcard(_chkvalue); check_result = (rv_result == '' ? true : false); curErrmsg = _cName + rv_result; break; } if (!check_result) {
  10. if (curErrmsg != '') { check_errmsg = etip + curErrmsg; } if ((curErrmsg != '') && (allowAlert)) { document.getElementById('saved').innerHTML = etip + curErrmsg; alert(etip + curErrmsg); return check_result; }
  11. }
  12. }
  13. return check_result;
  14. }
  15. function checkIdcard(idcard) {
  16. var _idcard = idcard; var Errors = new Array('', '身份证号码位数不对!', '身份证号码出生日期超出范围或含有非法字符!', '身份证号码校验错误!', '身份证地区非法!', '');
  17. if (_idcard == '') { return Errors[5]; }
  18. var area = { 11: '北京', 12: '天津', 13: '河北', 14: '山西', 15: '内蒙古', 21: '辽宁', 22: '吉林', 23: '黑龙江', 31: '上海', 32: '江苏', 33: '浙江', 34: '安徽', 35: '福建', 36: '江西', 37: '山东', 41: '河南', 42: '湖北', 43: '湖南', 44: '广东', 45: '广西', 46: '海南', 50: '重庆', 51: '四川', 52: '贵州', 53: '云南', 54: '西藏', 61: '陕西', 62: '甘肃', 63: '青海', 64: '宁夏', 65: '新疆', 71: '台湾', 81: '香港', 82: '澳门', 91: '国外' }
  19. var _idcard, Y, JYM; var S, M; var idcard_array = new Array(); idcard_array = _idcard.split('');
  20. if (area[parseInt(_idcard.substr(0, 2))] == null) { return Errors[4]; }
  21. switch (_idcard.length) {
  22. case 15: if ((parseInt(_idcard.substr(6, 2)) + 1900) % 4 == 0 || ((parseInt(_idcard.substr(6, 2)) + 1900) % 100 == 0 && (parseInt(_idcard.substr(6, 2)) + 1900) % 4 == 0)) {
  23. ereg = /^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$/;
  24. } else {
  25. ereg = /^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$/;
  26. }
  27. if (ereg.test(_idcard)) {
  28. var iS = 0; var iW = new Array; iW[0] = 7; iW[1] = 9; iW[2] = 10; iW[3] = 5; iW[4] = 8; iW[5] = 4; iW[6] = 2; iW[7] = 1; iW[8] = 6; iW[9] = 3; iW[10] = 7; iW[11] = 9; iW[12] = 10; iW[13] = 5; iW[14] = 8; iW[15] = 4; iW[16] = 2;
  29. var LastCode = '10X98765432'; var perIDNew; perIDNew = _idcard.substr(0, 6); perIDNew += '19'; perIDNew += _idcard.substr(6, 9);
  30. for (var i = 0; i < 17; i++) { iS += parseInt(perIDNew.substr(i, 1)) * iW[i]; }
  31. var iY = iS % 11; perIDNew += LastCode.substr(iY, 1);
  32. return Errors[0];
  33. } else {
  34. return Errors[2];
  35. }
  36. break;
  37. case 18: if (parseInt(_idcard.substr(6, 4)) % 4 == 0 || (parseInt(_idcard.substr(6, 4)) % 100 == 0 && parseInt(_idcard.substr(6, 4)) % 4 == 0)) {
  38. ereg = _idcard.substr(6, 2) == '19' ? /^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$/ : /^[1-9][0-9]{5}20[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$/;
  39. } else {
  40. ereg = _idcard.substr(6, 2) == '19' ? /^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$/ : /^[1-9][0-9]{5}20[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$/;
  41. }
  42. if (ereg.test(_idcard)) {
  43. S = (parseInt(idcard_array[0]) + parseInt(idcard_array[10])) * 7 + (parseInt(idcard_array[1]) + parseInt(idcard_array[11])) * 9 + (parseInt(idcard_array[2]) + parseInt(idcard_array[12])) * 10 + (parseInt(idcard_array[3]) + parseInt(idcard_array[13])) * 5 + (parseInt(idcard_array[4]) + parseInt(idcard_array[14])) * 8 + (parseInt(idcard_array[5]) + parseInt(idcard_array[15])) * 4 + (parseInt(idcard_array[6]) + parseInt(idcard_array[16])) * 2 + parseInt(idcard_array[7]) * 1 + parseInt(idcard_array[8]) * 6 + parseInt(idcard_array[9]) * 3;
  44. Y = S % 11; M = 'F'; JYM = '10X98765432'; M = JYM.substr(Y, 1); if (M == idcard_array[17]) return Errors[0]; else { return Errors[3]; }
  45. } else { return Errors[2]; } break; default: return Errors[1]; break;
  46. }
  47. }
  48. function getid(id) { alert(checkIdcard(id)) }
  49. function per18To15(perIDSrc) { rstr = ''; for (var i = 0; i < 17; i++) { if ((i == 6) || (i == 7)) { continue; } rstr += perIDSrc.charAt(i); } return rstr; }
  50. function per15To18(perIDSrc) {
  51. var iS = 0; var iW = new Array;
  52. iW[0] = 7; iW[1] = 9; iW[2] = 10; iW[3] = 5; iW[4] = 8; iW[5] = 4; iW[6] = 2; iW[7] = 1; iW[8] = 6; iW[9] = 3; iW[10] = 7; iW[11] = 9; iW[12] = 10; iW[13] = 5; iW[14] = 8; iW[15] = 4; iW[16] = 2;
  53. var LastCode = '10X98765432'; var perIDNew; perIDNew = perIDSrc.substr(0, 6); perIDNew += '19'; perIDNew += perIDSrc.substr(6, 9);
  54. for (var i = 0; i < 17; i++) { iS += parseInt(perIDNew.substr(i, 1)) * iW[i]; }
  55. var iY = iS % 11; perIDNew += LastCode.substr(iY, 1); return perIDNew;
  56. }
  57. var aCity = { 11: '北京', 12: '天津', 13: '河北', 14: '山西', 15: '内蒙古', 21: '辽宁', 22: '吉林', 23: '黑龙江', 31: '上海', 32: '江苏', 33: '浙江', 34: '安徽', 35: '福建', 36: '江西', 37: '山东', 41: '河南', 42: '湖北', 43: '湖南', 44: '广东', 45: '广西', 46: '海南', 50: '重庆', 51: '四川', 52: '贵州', 53: '云南', 54: '西藏', 61: '陕西', 62: '甘肃', 63: '青海', 64: '宁夏', 65: '新疆', 71: '台湾', 81: '香港', 82: '澳门', 91: '国外' }
  58. function cidInfo(sId) {
  59. var iSum = 0; var info = '';
  60. if (!/^\d{17}(\d|x)$/i.test(sId))
  61. return false; sId = sId.replace(/x$/i, 'a');
  62. if (aCity[parseInt(sId.substr(0, 2))] == null) return 'Error:非法地区'; sBirthday = sId.substr(6, 4) + '-' + Number(sId.substr(10, 2)) + '-' + Number(sId.substr(12, 2));
  63. var d = new Date(sBirthday.replace(/-/g, '/'))
  64. if (sBirthday != (d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate()))
  65. return 'Error:非法生日';
  66. for (var i = 17; i >= 0; i--) iSum += (Math.pow(2, i) % 11) * parseInt(sId.charAt(17 - i), 11)
  67. if (iSum % 11 != 1) return 'Error:非法证号';
  68. return aCity[parseInt(sId.substr(0, 2))] + ',' + sBirthday + ',' + (sId.substr(16, 1) % 2 ? '男' : '女')
  69. }
  70. function PositionLen(s){var i,str1,str2,str3,nLen; str1 =s;nLen = 0;for(i=1;i<=str1.length;i++){str2=str1.substring(i-1,i);str3=escape(str2);if(str3.length>3){ nLen = nLen + 2;}else{nLen = nLen + 1;} }
  71. return nLen;}
  72. function isNotNull(str){return (str==''?false:true);}
  73. function isNumber(str){if(str==''){return true;}return (isNaN(str)?false:true);}
  74. function isNumber(str){if(str==''){return true;}return (isNaN(str)?false:true);}
  75. function isBNumber(str){if(str==''){return true;}return (!isNaN(str)?parseInt(str,10)>=0?true:false:false);}
  76. function isSNumber(str){if(str==''){return true;}return (!isNaN(str)?parseInt(str,10)<0?true:false:false);}
  77. function isAlpha(_str){return (_str.replace(/\w/g,'').length == 0);}
  78. function isAN(_str){var reg = /^(([a-z]+[0-9]+)|([0-9]+[a-z]+))[a-z0-9]*$/i;return reg.test(_str);}
  79. function validRegs(_value,_Regs){return _Regs.test(_value); }
  80. function isVisibled(obj){ if( (obj.style.display=='none')||( (obj.offsetHeight==0)&&(obj.offsetWidth==0) ) ) return false; if(obj.currentStyle){if(obj.currentStyle['display']=='none') return false;} return true;}
  81. function isFocused(obj){ if( (obj.disabled==false)&&(isVisibled(obj)) ) return true; return false;}
  82. function isDate(str,cname,notip){if(str==''){return true;}
  83. str=str.replace(/\//g,'-');
  84. dt=str.split(' ');if(dt.length>2){if(!notip) alert(cname+'日期输入不正确!可能包括非法的日期组成部分。');return false; } dt1=dt[0].split('-');if(dt1.length!=3){if(!notip) alert(cname+'日期输入不正确!日期部分应为YYYY-MM-DD。');return false;}dt1n=(dt1[0]+dt1[1]+dt1[2]).split('');for(var i=0;i<dt1.length;i++){if((isNaN(dt1[i])||(ctrim(dt1[i])==''))){if(!notip) alert(cname+'字符:'+dt1[i]+',年月日部分必须输入数字!'); return false;} }_year=parseInt(dt1[0],10); _month=parseInt(dt1[1],10); _day=parseInt(dt1[2],10);if((_year<1000)||(_year>9999)||(_month<1)||(_month>12)||(_day<1)||(_day>31)){if(!notip) alert(cname+'年月日部分输入的数字不合理,请核对!');return false; }v_date31=new Array;v_date31[0]=4;v_date31[1]=6;v_date31[2]=9;v_date31[3]=11;if((getArrayIndex(v_date31,_month)!=-1)&&(_day>30)){if(!notip) alert(cname+'月份:'+_month+',天数输入范围不合理!'); return false;}if(_month==2){ if(((_year%4==0)&&(_year%100!=0))||(_year%400==0)){ if(_day>29){if(!notip) alert(cname+'月份:'+_month+',天数输入范围不合理!');return false; }}else{ if(_day>28){if(!notip) alert(cname+'月份:'+_month+',天数输入范围不合理!');return false; }} } return true; }
  85. function getArrayIndex(xArray,find){_rs=-1;for(var j=0;j<xArray.length;j++){if(xArray[j]==find){_rs=j; break; }} return _rs; }
  86. function ctrim(ename){ if(ename==undefined) return ''; return (ename.replace(/(^\s*)|(\s*$)/g, '')).replace(/^[\s \t]+|[\s \t]+$/, '');}
  87. var RowsCount = 0;
  88. var ErrorMessage = "";
  89. function swarp(mId, stype) {
  90. var mObj = document.getElementById(mId);
  91. if (mObj == undefined) {
  92. return false;
  93. }
  94. var premObj = mObj.previousElementSibling;
  95. if (stype == 2) {
  96. premObj = mObj.nextElementSibling;
  97. }
  98. if (premObj == null) return false;
  99. if (stype == 1) {
  100. mObj.parentNode.insertBefore(mObj, premObj);
  101. } else if (stype == 2) {
  102. mObj.parentNode.insertBefore(premObj, mObj);
  103. }
  104. }
  105. function setrow(rowobj) {
  106. document.getElementById('curid').value = rowobj.id;
  107. chnRowSelColor(rowobj);
  108. }
  109. function chnRowSelColor(rowobj) {
  110. var _com = "att_" + document.getElementById('com_name').value;
  111. var mt = document.getElementById('mtable');
  112. for (var i = 0; i < mt.rows.length; i++) {
  113. var mt_row = mt.rows[i];
  114. mt_row.style.backgroundColor = '';
  115. if (mt_row.id == rowobj.id) {continue;}
  116. for (var j = 0; j < mt_row.cells.length; j++) {
  117. var cell1 = mt_row.cells[j];
  118. if (cell1.getElementsByTagName('input').length > 0) {
  119. cell1.innerHTML = cell1.getElementsByTagName('input')[0].value.replace(/<[^>]*>/g, '');
  120. }else
  121. if (cell1.getElementsByTagName('select').length > 0) {
  122. cell1.innerHTML = cell1.getElementsByTagName('select')[0].value.replace(/<[^>]*>/g, '');
  123. }
  124. }
  125. }
  126. rowobj.style.backgroundColor = 'rgb(235,235,235)';
  127. var pj = JSON.parse(document.getElementById('pjson').value);
  128. var jtcy = pj[_com][0].cols;
  129. var isadd = false;
  130. if (rowobj.cells.length == 0) {
  131. isadd = true;
  132. }
  133. for (var i = 0; i < jtcy.length; i++) {
  134. var cell1 = isadd==true?rowobj.insertCell(i):rowobj.cells[i];
  135. var ctype = jtcy[i].input;
  136. var innerhtml = "";
  137. var oldvalue = "";
  138. if(isadd==true){
  139. cell1.setAttribute("checkSchema",jtcy[i].check);
  140. cell1.setAttribute("cName",jtcy[i].cname);
  141. }
  142. if (ctype == "text") {
  143. oldvalue = cell1.innerText;
  144. innerhtml = "<input type='" + ctype + "' onchange='validchange(this)' placeholder='" + jtcy[i].cname + "'style='" + jtcy[i].ctl_style + "'/>";
  145. } else if (ctype == "select") {
  146. oldvalue = cell1.innerText;
  147. innerhtml = "<" + ctype + " onchange='validchange(this)' style='" + jtcy[i].ctl_style + "' />";
  148. innerhtml += "<option value=''>" + jtcy[i].cname + "</option>";
  149. var items = jtcy[i].list.split("|");
  150. for (var j = 0; j < items.length; j++) {
  151. innerhtml += "<option>" + items[j] + "</option>";
  152. }
  153. innerhtml += "</" + ctype + ">";
  154. }
  155. cell1.innerHTML = innerhtml;
  156. cell1.style = jtcy[i].td_style;
  157. cell1.addEventListener('click', function (event) {
  158. event.stopPropagation();
  159. if (cell1.parentNode.id != document.getElementById('curid').value) {
  160. setrow(cell1.parentNode);
  161. }
  162. });
  163. if (cell1.getElementsByTagName('input').length > 0) {
  164. cell1.getElementsByTagName('input')[0].value=oldvalue;
  165. cell1.getElementsByTagName('input')[0].addEventListener('click', function (event) {
  166. event.stopPropagation();
  167. });
  168. } else if (cell1.getElementsByTagName('select').length > 0) {
  169. cell1.getElementsByTagName('select')[0].value = oldvalue;
  170. cell1.getElementsByTagName('select')[0].addEventListener('click', function (event) {
  171. event.stopPropagation();
  172. });
  173. }
  174. }
  175. }
  176. function ss(type, result) {
  177. try {
  178. var robj = JSON.parse(result);
  179. if (robj.errcode != 0) {
  180. ErrorMessage = robj.errmsg;
  181. alert(ErrorMessage);
  182. } else {
  183. RowsCount++;
  184. }
  185. } catch (ss_e) {
  186. ErrorMessage=(ss_e);
  187. alert(ErrorMessage);
  188. }
  189. if (RowsCount == document.getElementById('mtable').rows.length) {
  190. document.getElementById('Button4').removeAttribute("disabled");
  191. document.getElementById('saved').style.color = 'green';
  192. document.getElementById('saved').innerHTML = "保存所有成功。";
  193. window.setTimeout(function () {
  194. document.getElementById('saved').style.color = 'red';
  195. document.getElementById('saved').innerHTML = "";
  196. }, 1000);
  197. callServerFunction("", "save_att_data", "{ypz_cid:'" +document.getElementById('cid').value+"',com_name:'"+document.getElementById('com_name').value + "'}", ss4);
  198. }
  199. }
  200. function ss4(type, result) {
  201. if (JSON.stringify(result) == "\"true\"") {
  202. } else {
  203. alert('同步更新简历信息失败,请点击修改简历按钮提交修改。' + JSON.stringify(result));
  204. }
  205. }
  206. function ss3(type, result) {
  207. try {
  208. var robj = JSON.parse(result);
  209. if (robj.errcode != 0) {
  210. ErrorMessage = robj.errmsg;
  211. alert(ErrorMessage);
  212. } else {
  213. RowsCount++;
  214. }
  215. } catch (ss3_e) {
  216. ErrorMessage = (ss3_e);
  217. alert(ErrorMessage);
  218. }
  219. }
  220. function tojsonstr(str) {
  221. var prv = str.replace(/["\\]/g, '\\$&').replace(/<[^>]*>/g, '').replace(/<[^>]*>/g, '') ;
  222. return prv;
  223. }
  224. function saveall() {
  225. var mt = document.getElementById('mtable');
  226. if (mt.rows.length == 0) {
  227. document.getElementById('saved').style.color = '#4169E1';
  228. document.getElementById('saved').innerHTML = "请添加行后再执行保存操作...";
  229. window.setTimeout(function () {
  230. document.getElementById('saved').style.color = 'red';
  231. document.getElementById('saved').innerHTML = "";
  232. }, 3000);
  233. return;
  234. }
  235. RowsCount = 0;
  236. ErrorMessage = "";
  237. document.getElementById('saved').style.color = '#4169E1';
  238. document.getElementById('saved').innerHTML = "正在保存...";
  239. var _com = "att_" + document.getElementById('com_name').value;
  240. var pj = JSON.parse(document.getElementById('pjson').value);
  241. var dj = JSON.parse(document.getElementById('djson').value);
  242. var jtcy = pj[_com][0].cols;
  243. for (var i = 0; i < mt.rows.length; i++) {
  244. var mt_row = mt.rows[i];
  245. dj.cid = mt_row.id;
  246. dj.sortid = (i + 1);
  247. for (var j = 0; j < mt_row.cells.length; j++) {
  248. var cell1 = mt_row.cells[j];
  249. var _value = cell1.innerText;
  250. if (cell1.getElementsByTagName('input').length > 0) {
  251. _value = cell1.getElementsByTagName('input')[0].value;
  252. } else if (cell1.getElementsByTagName('select').length > 0) {
  253. _value = cell1.getElementsByTagName('select')[0].value;
  254. }
  255. dj[jtcy[j].fname] =tojsonstr(_value);
  256. }
  257. callServerFunction("", "saveInfo", "{jdata:'" + JSON.stringify(dj).replace(/['\\]/g, '\\$&') + "'}", ss);
  258. }
  259. }
  260. function ss2(type, result) {
  261. try {
  262. var robj = JSON.parse(result);
  263. if (robj.errcode != 0) {
  264. ErrorMessage = robj.errmsg;
  265. alert(ErrorMessage);
  266. } else {
  267. RowsCount++;
  268. var curid = document.getElementById('curid').value;
  269. var mt_row = document.getElementById(curid);
  270. document.getElementById('mtable').deleteRow(mt_row.rowIndex);
  271. document.getElementById('saved').style.color = 'red';
  272. document.getElementById('saved').innerHTML = "";
  273. alert('删除当前行成功!');
  274. }
  275. } catch (ss2_e) {
  276. ErrorMessage = (ss2_e);
  277. alert(ErrorMessage);
  278. }
  279. }
  280. function delinfo() {
  281. var curid = document.getElementById('curid').value;
  282. if (curid == "") {
  283. alert('请选中记录后再执行删除操作。');
  284. return;
  285. }
  286. RowsCount = 0;
  287. ErrorMessage = "";
  288. var _com = "att_" + document.getElementById('com_name').value;
  289. var dj = JSON.parse(document.getElementById('djson').value);
  290. var mt_row = document.getElementById(curid);
  291. dj.cid = mt_row.id;
  292. callServerFunction("", "deleteInfo", "{jdata:'" + JSON.stringify(dj).replace(/['\\]/g, '\\$&') + "'}", ss2);
  293. }
  294. function validall(extip) {
  295. var _com = "att_" + document.getElementById('com_name').value;
  296. var mt = document.getElementById('mtable');
  297. var pj = JSON.parse(document.getElementById('pjson').value);
  298. var dj = JSON.parse(document.getElementById('djson').value);
  299. var jtcy = pj[_com][0].cols;
  300. for (var i = 0; i < mt.rows.length; i++) {
  301. var mt_row = mt.rows[i];
  302. for (var j = 0; j < mt_row.cells.length; j++) {
  303. var cell1 = mt_row.cells[j];
  304. var _value = cell1.innerText;
  305. if (cell1.getElementsByTagName('input').length > 0) {
  306. _value = cell1.getElementsByTagName('input')[0].value;
  307. } else if (cell1.getElementsByTagName('select').length > 0) {
  308. _value = cell1.getElementsByTagName('select')[0].value;
  309. }
  310. var isvalid = simplecheck(cell1, _value, true, extip+"第" + (i + 1) + "行:");
  311. if (isvalid == false) {
  312. mt_row.style.backgroundColor = '#B22222';
  313. return false;
  314. }
  315. }
  316. }
  317. return true;
  318. }
  319. function validchange(obj) {
  320. document.getElementById('saved').innerText = '修改了'+obj.parentNode.getAttribute('cname')+'待保存';
  321. }
  322. function validsave(extip) {
  323. if (document.getElementById('saved').innerText != '') {
  324. return false;
  325. }
  326. return true;
  327. }
  328. function addRow() {
  329. if (validall('') == false) {
  330. return;
  331. }
  332. RowsCount = 0;
  333. ErrorMessage = "";
  334. var _com = "att_" + document.getElementById('com_name').value;
  335. var pj = JSON.parse(document.getElementById('pjson').value);
  336. var jtcy=pj[_com][0].cols;
  337. var mt = document.getElementById('mtable');
  338. var maxCount = parseInt(pj[_com][0].maxRowCount, 10);
  339. if (mt.rows.length >= maxCount) {
  340. alert("本内容最多允许添加" + maxCount + "行。");
  341. return;
  342. }
  343. var row = mt.insertRow(-1); // -1 表示在表的末尾插入新行
  344. row.id = gGuid();
  345. row.setAttribute("onclick", "setrow(this)");
  346. setrow(row);
  347. var dj = JSON.parse(document.getElementById('djson').value);
  348. dj["cid"] = row.id;
  349. dj["sortid"] = mt.rows.length;
  350. callServerFunction("", "saveInfo", "{jdata:'" + JSON.stringify(dj) + "'}", ss3);
  351. document.getElementById('saved').style.color = 'red';
  352. document.getElementById('saved').innerHTML = "添加新行未保存";
  353. ScrollToBottom();
  354. }
  355. function gGuid() {
  356. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  357. var r = Math.floor(Math.random() * 16);
  358. var v = c === 'x' ? r : (r & 0x3 | 0x8);
  359. return v.toString(16);
  360. });
  361. }
  362. function ScrollToBottom() {
  363. $("html, body").animate({ scrollTop: $(document).height() - $(window).height() });
  364. }
  365. </script>

Jquery引用

这是一组基于Jquery的自定义开发的扩展应用库,请下载我的资源:

https://download.csdn.net/download/michaelline/88615565

进行引用,本库用于调用服务器静态方法等功能使用。

C# 服务端操作 

服务端主要用于对已有数据的提取显示并初始化到主编辑表中的行,并提供保存及删除操作的静态方法,主要方法说明见下表:

序号方法名返回类型说明
1public void InitPage()void主要用于提取已有数据表数据并显示到主编辑表 mtable 的数据行,如何提取数据请参照我的文章

 《C# 利用IDbDataAdapter / IDataReader 实现通用数据集获取》 

2public static string saveInfo(string jdata)string

保存行信息到数据表,参数为提交的Json数据包,

保存数据操作请参照我的文章《C#利用IDbCommand实现通用数据库脚本执行程序》

3public static string deleteInfo(string jdata)string删除行信息到数据表,参数为提交的Json数据包,保存数据库操作请参照我的文章《C#利用IDbCommand实现通用数据库脚本执行程序》
4private static string String2Json(String s)string规范字符串,以符合Json字符串要求

实现示例代码如下:

  1. <%@ Page Language="C#" %>
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <%@ Import Namespace="System.Data"%>
  4. <%@ Import NameSpace="System.Data.SqlClient"%>
  5. <%@ Import Namespace="System.IO"%>
  6. <%@ Import Namespace="System.Web.Services"%>
  7. <script language="C#" runat="server">
  8. public CosysJaneCommonAPI.CODAL dal = new CosysJaneCommonAPI.CODAL();
  9. void Page_Load(Object sender, EventArgs e)
  10. {
  11. if (Page.IsPostBack) { return; }
  12. InitPage();
  13. }
  14. public void InitPage()
  15. {
  16. dal.RunAt = Page.Form;
  17. string _xmbh = "001";
  18. string _p_att_json = pjson.Text;
  19. string _sfzh = "120102";
  20. xmbh.Text = _xmbh;
  21. sfzh.Text = _sfzh;
  22. com_name.Text = Request.QueryString["com_name"];
  23. Newtonsoft.Json.Linq.JObject jobj = Newtonsoft.Json.Linq.JObject.Parse(pjson.Text);
  24. djson.Text = "{";
  25. _sql = "select ";
  26. HtmlTableRow trow = new HtmlTableRow();
  27. ttable.Attributes["style"] = jobj["att_" + com_name.Text][0]["ttable_style"].ToString();
  28. mtable.Attributes["style"] = jobj["att_" + com_name.Text][0]["mtable_style"].ToString();
  29. for (int i = 0; i < jobj["att_" + com_name.Text][0]["cols"].Count(); i++)
  30. {
  31. HtmlTableCell tcell = new HtmlTableCell();
  32. tcell.InnerText = jobj["att_" + com_name.Text][0]["cols"][i]["cname"].ToString();
  33. tcell.Attributes["style"] = jobj["att_" + com_name.Text][0]["cols"][i]["td_style"].ToString();
  34. trow.Cells.Add(tcell);
  35. djson.Text += string.Format("\"{0}\":\"{1}\",", jobj["att_" + com_name.Text][0]["cols"][i]["fname"].ToString(), "");
  36. _sql += jobj["att_" + com_name.Text][0]["cols"][i]["fname"].ToString() + ",";
  37. }
  38. ttable.Rows.Add(trow);
  39. djson.Text += string.Format("\"{0}\":\"{1}\"", "xmbh", _xmbh);
  40. djson.Text += string.Format(",\"{0}\":\"{1}\"", "sfzh",_sfzh);
  41. djson.Text += string.Format(",\"{0}\":\"{1}\"", "sortid", "");
  42. djson.Text += string.Format(",\"{0}\":\"{1}\"", "cid", "");
  43. djson.Text += string.Format(",\"{0}\":\"{1}\"", "com_name", com_name.Text);
  44. djson.Text += "}";
  45. _sql = _sql + "cid from att_" + com_name.Text+" where xmbh=@xmbh and sfzh=@sfzh order by sortid";
  46. paras.Clear();
  47. paras.Add(new SqlParameter("xmbh", _xmbh));
  48. paras.Add(new SqlParameter("sfzh", _sfzh));
  49. rv = dal.GetDataSet(_sql, paras);
  50. if (dal.ErrorMessage != "")
  51. {
  52. return;
  53. }
  54. topnavs.Visible = true;
  55. ttable.Style["top"] = "37px";
  56. mtable.Style["top"] = "67px";
  57. if (dal.RowsCount == 0)
  58. {
  59. return;
  60. }
  61. dt = ((DataSet)rv).Tables[0];
  62. for (int i = 0; i < dt.Rows.Count; i++)
  63. {
  64. HtmlTableRow hrow = new HtmlTableRow();
  65. if (_zwmc == "" || (_bcbz == "true" && _bcsm != ""))
  66. {
  67. hrow.Attributes["onclick"] = "setrow(this)";
  68. }
  69. hrow.ID = dt.Rows[i]["cid"].ToString();
  70. for (int j = 0; j < dt.Columns.Count-1; j++)
  71. {
  72. HtmlTableCell hcell = new HtmlTableCell();
  73. hcell.Attributes["style"] = jobj["att_" + com_name.Text][0]["cols"][j]["td_style"].ToString();
  74. hcell.Attributes["cName"] = jobj["att_" + com_name.Text][0]["cols"][j]["cname"].ToString();
  75. hcell.Attributes["checkSchema"] = jobj["att_" + com_name.Text][0]["cols"][j]["check"].ToString();
  76. hcell.InnerText = dt.Rows[i][dt.Columns[j].ToString()].ToString();
  77. hrow.Cells.Add(hcell);
  78. }
  79. mtable.Rows.Add(hrow);
  80. }
  81. }
  82. [WebMethod(BufferResponse = true)]
  83. public static string saveInfo(string jdata)
  84. {
  85. Newtonsoft.Json.Linq.JObject jobj = Newtonsoft.Json.Linq.JObject.Parse(jdata);
  86. string tablename = "";
  87. string inssql = "";
  88. string inslist = "";
  89. string insparas = "";
  90. string updsql = "";
  91. string updparas = "";
  92. ArrayList paras = new ArrayList();
  93. paras.Clear();
  94. foreach (KeyValuePair<string, Newtonsoft.Json.Linq.JToken> kvp in jobj)
  95. {
  96. string key = kvp.Key.ToString();
  97. string value = kvp.Value.ToString();
  98. if (key == "com_name" && (value == "jtcy" || value == "shgx" || value == "jypx" || value == "gzjl"))
  99. {
  100. tablename = "att_"+value;
  101. }
  102. else
  103. {
  104. inslist += key + ",";
  105. insparas +="@"+ key + ",";
  106. updparas += string.Format(" {0}=@{1},",key,key);
  107. paras.Add(new SqlParameter(key, value));
  108. }
  109. }
  110. if (inslist.Length > 1)
  111. {
  112. inslist = inslist.Substring(0, inslist.Length - 1);
  113. insparas = insparas.Substring(0, insparas.Length - 1);
  114. inssql = string.Format("insert into {0} ({1}) values({2});", tablename, inslist, insparas);
  115. }
  116. if (updparas.Length > 1)
  117. {
  118. updparas = updparas.Substring(0, updparas.Length - 1);
  119. updsql = string.Format("update {0} set {1} where cid=@cid;", tablename, updparas);
  120. }
  121. string sql = string.Format(" if not exists(select cid from {0} where cid=@cid) begin {1} end else begin {2} end", tablename, inssql, updsql);
  122. CosysJaneCommonAPI.CODAL dal = new CosysJaneCommonAPI.CODAL();
  123. dal.ExecDbScripts(sql, paras);
  124. string rv = "{\"errcode\":0,\"errmsg\":\"\"}";
  125. if (dal.ErrorMessage != "")
  126. {
  127. rv="{\"errcode\":2,\"errmsg\":\""+String2Json(dal.ErrorMessage)+"\"}";
  128. }
  129. else if (dal.RowsCount == 0)
  130. {
  131. rv = "{\"errcode\":1,\"errmsg\":\"" + String2Json("未成功更新记录。") + "\"}";
  132. }
  133. return rv;
  134. }
  135. [WebMethod(BufferResponse = true)]
  136. public static string deleteInfo(string jdata)
  137. {
  138. Newtonsoft.Json.Linq.JObject jobj = Newtonsoft.Json.Linq.JObject.Parse(jdata);
  139. string tablename = "";
  140. string updsql = "";
  141. string updparas = "";
  142. ArrayList paras = new ArrayList();
  143. paras.Clear();
  144. foreach (KeyValuePair<string, Newtonsoft.Json.Linq.JToken> kvp in jobj)
  145. {
  146. string key = kvp.Key.ToString();
  147. string value = kvp.Value.ToString();
  148. if (key == "com_name" && (value == "jtcy" || value == "shgx"|| value == "jypx" || value == "gzjl"))
  149. {
  150. tablename = "att_"+value;
  151. }
  152. else if(key=="cid")
  153. {
  154. paras.Add(new SqlParameter(key, value));
  155. }
  156. }
  157. updsql = string.Format("delete from {0} where cid=@cid;", tablename);
  158. CosysJaneCommonAPI.CODAL dal = new CosysJaneCommonAPI.CODAL();
  159. dal.ExecDbScripts(updsql, paras);
  160. string rv = "{\"errcode\":0,\"errmsg\":\"\"}";
  161. if (dal.ErrorMessage != "")
  162. {
  163. rv = "{\"errcode\":2,\"errmsg\":\"" + String2Json(dal.ErrorMessage) + "\"}";
  164. }
  165. else if (dal.RowsCount == 0)
  166. {
  167. rv = "{\"errcode\":1,\"errmsg\":\"" + String2Json("未成功更新记录。") + "\"}";
  168. }
  169. return rv;
  170. }
  171. private static string String2Json(String s)
  172. {
  173. StringBuilder sb = new StringBuilder();
  174. for (int i = 0; i < s.Length; i++)
  175. {
  176. char c = s.ToCharArray()[i];
  177. switch (c)
  178. {
  179. case '\"':
  180. sb.Append("\\\""); break;
  181. case '\\':
  182. sb.Append("\\\\"); break;
  183. case '/':
  184. sb.Append("\\/"); break;
  185. case '\b':
  186. sb.Append("\\b"); break;
  187. case '\f':
  188. sb.Append("\\f"); break;
  189. case '\n':
  190. sb.Append("\\n"); break;
  191. case '\r':
  192. sb.Append("\\r"); break;
  193. case '\t':
  194. sb.Append("\\t"); break;
  195. default:
  196. if ((c >= 0 && c <= 31) || c == 127)//在ASCⅡ码中,第0~31号及第127号(共33个)是控制字符或通讯专用字符
  197. {
  198. }
  199. else
  200. {
  201. sb.Append(c);
  202. }
  203. break;
  204. }
  205. }
  206. return sb.ToString();
  207. }
  208. </script>

小结

由于一对多录入的特点,我们采用了嵌入 iframe 元素的方法,然后传递参数名称 com_name,以决定使用Json配置文件中的节点信息 。

正常的情况下,我们还会有父项的录入界面,并提供有保存按钮,因此点击保存按钮时客户端可能还需要对 iframe 里的表格数据再进行一次校验或处理,访问iframe里的元素方法主要通过iframe.contentWindow.document 处理,比如如下代码:

  1. var atts = new Array();
  2. atts.push('att_jypx');
  3. function before_submit() {
  4. for (var i = 0; i < atts.length; i++) {
  5. var p_att = document.getElementById('p_' + atts[i]);
  6. if (p_att == undefined) { continue; }
  7. var p_att_ifr = document.getElementById('x_p_' + atts[i]);
  8. var l_att = document.getElementById('l_' + atts[i]);
  9. if (p_att_ifr.contentWindow.document.getElementById('mtable').rows.length == 0) {
  10. alert(l_att.innerText + "的内容需要添加。");
  11. return false;
  12. }
  13. if (p_att_ifr.contentWindow.validall(l_att.innerText+"内容的") == false) {
  14. return false;
  15. }
  16. if (p_att_ifr.contentWindow.validsave('')== false) {
  17. alert(l_att.innerText + "的内容有尚未或正在保存的内容,请保存后再进行提交。");
  18. return false;
  19. }
  20. }
  21. return true;
  22. }

​另外工具栏按钮的图片文件,我们可以按照自己的实际需要进行替换。本代码仅供您参考使用,感谢您的阅读,希望本文能够对您有所帮助。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/614528
推荐阅读
相关标签
  

闽ICP备14008679号