• ASP.NET如何批量保存动态生成的文本框?


    对于OA系统,表单签核功能必不可少。而根据公司的情况,表单自然又五花八门,所以就要求能够让用户自己建立表单并设定表单的流程、填写内容等等。我之前写过一篇文章【地址:pivot的用法(SQL SERVER 2005 以上)】,对于OA系统这些填写内容的数据表结构作过一定的说明,而今天,我会给大家说明一下,用户在新建表单时,填表填到一半时,怎么暂存所填写的内容(此原理适用于表单提交时的保存操作)。

    1、首先,以下面这张table为例子说明,其中【colValue】为用户填写的内容:

    图一、表格详情

    2、其次,我们需要把这些内容输出到页面,输出的话,比较简单,新建一个WebBaseSetup.aspx文件,以下为源码:

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebBaseSetup.aspx.cs" Inherits="Admin_WebBaseSetup" %>
    
    <!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>網址導覽設定</title>
        <link href="../css/main.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
        <form id="form1" runat="server">
        <div style="600px;">
            <input type="button" id="btnSave"  value="保存" style="50px" />
            <asp:Literal ID="ltList" runat="server"></asp:Literal>
        </div>
        </form>
    </body>
    </html>


    3、至于WebBaseSetup.aspx.cs文件的源码如下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Text;
    
    public partial class Admin_WebBaseSetup : clsCheckRole
    {
        clsBaseSetup oBaseSetup = new clsBaseSetup();
    
        private readonly string _colValue = "colValue_";
        private readonly string _colDesction = "colDesction_";
    
        protected void Page_Load(object sender, EventArgs e)
        {
            ckSession();
            if (!IsPostBack)
            {
                BindData();
            }
        }
    
        private void BindData()
        {
            var baseList = oBaseSetup.GetBaseSetupList();
            if (baseList.Any())
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("<table class='tbinfo' border='0' cellpadding='0' cellspacing='1' style='background-color:#D9E6FF;'>
    ");
                sb.Append("<tr><th style='130px;'>變量名</th><th style='70px;'>數值</th><th>備注</th></tr>");
                foreach (var item in baseList)
                {
                    sb.AppendFormat("<tr>
    <td>{0}</td>
    ", item.colName);
                    sb.AppendFormat("<td style='text-align:center;'><input type='input' name='{0}' class='colControl' value='{1}' style='40px;' /></td>
    ", _colValue + item.id, item.colValue);
                    sb.AppendFormat("<td><input type='input' name='{0}' class='colControl' value='{1}' style='98%;' /></td>
    <tr>
    ", _colDesction + item.id, item.colDesction);
                }
                sb.Append("</table>");
                ltList.Text = sb.ToString();
            }
        }
    }


    4、需要引用的clsBaseSetup.cs类源码如下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Data.SqlClient;
    
    /// <summary>
    /// clsBaseSetup 的摘要说明
    /// </summary>
    public class clsBaseSetup
    {
    
        #region model
        /// <summary>
        /// 主鍵
        /// </summary>
        public string id { get; set; }
    
        /// <summary>
        /// 系統標識名稱
        /// </summary>
        public string colName { get; set; }
    
        /// <summary>
        /// 設定值
        /// </summary>
        public string colValue { get; set; }
    
        /// <summary>
        /// 說明
        /// </summary>
        public string colDesction { get; set; }
        #endregion
        public clsBaseSetup()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }
    
        #region method
    
        /// <summary>
        /// 返回基礎設定表中的所有設定項
        /// </summary>
        /// <returns></returns>
        public List<clsBaseSetup> GetBaseSetupList()
        {
            List<clsBaseSetup> list = new List<clsBaseSetup>();
            string sql = "SELECT id,colName,colValue,colDesction FROM CWNS_BaseSetUp_Tab ORDER BY colName";
            using (SqlDataReader dr = DbHelperSQL.ExecuteReader(sql))
            {
                while (dr.Read())
                {
                    list.Add(GetModel(dr));
                }
            }
            return list;
        }
    
        /// <summary>
        /// 獲取基礎設定表中的設定項
        /// </summary>
        /// <param name="colName">字段名</param>
        /// <param name="defaultValue">如果抓不到值則取默認值</param>
        /// <returns></returns>
        public Object GetColValueByColName(string colName, string defaultValue)
        {
            string sql = string.Format("SELECT ISNULL(colValue,'{0}') FROM CWNS_BaseSetUp_Tab WHERE colName='{1}'", defaultValue, colName);
            Object obj = DbHelperSQL.GetSingle(sql);
            if (obj == null)
            {
                obj = defaultValue;
            }
            return obj;
        }
        #endregion
    
        #region 私有方法
        /// <summary>
        /// 獲取實體
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        private clsBaseSetup GetModel(SqlDataReader dr)
        {
            return new clsBaseSetup
            {
                id = dr["id"].ToString(),
                colName = dr["colName"].ToString(),
                colValue = dr["colValue"].ToString(),
                colDesction = dr["colDesction"].ToString()
            };
        }
        #endregion
    }

    5、好了,到了这步以后,运行网站,看到的界面应该会类似于下面这张图的,当然,CSS文件没提供,所以样式可能不一样,可以自己调:

     图二、预览效果图

     

    6、右键浏览器查看它生成的那个table的代码如下:

    <table class='tbinfo' border='0' cellpadding='0' cellspacing='1' style='background-color:#D9E6FF;'>
      <tr>
        <th style='130px;'>變量名</th>
        <th style='70px;'>數值</th>
        <th>備注</th>
      </tr>
      <tr>
        <td>Navigate_maxCount</td>
        <td style='text-align:center;'><input type='input' name='colValue_2' class='colControl' value='100' style='40px;' /></td>
        <td><input type='input' name='colDesction_2' class='colControl' value='設置網址導覽首頁每分類下顯示的最大項目數量' style='98%;' /></td>
      <tr>
      <tr>
        <td>Navigate_rowNum</td>
        <td style='text-align:center;'><input type='input' name='colValue_1' class='colControl' value='6' style='40px;' /></td>
        <td><input type='input' name='colDesction_1' class='colControl' value='設置綱址導覽首頁每行顯示多少項' style='98%;' /></td>
      <tr>
    </table>

    7、下面接下来的动作,就是编写【保存】按钮的动作了,目标是把input的表单打包传输到后台的一个处理程序处理,可以用jquery操作:

     在【WebBaseSetup.aspx】的head标签中加入以下代码:

        <script src="../js/jquery-1.6.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(function () {
                $("#btnSave").click(function () {
                    SaveColValue();
                });
            });
    
            function SaveColValue() {//保存欄位值
                var param = $(".tbinfo").find('.colControl').serializeArray();
                param.push({ name: 'Action', value: 'Save' });
                jQuery.ajax({
                    url: '../ajax/UpdateBaseSetupColValue.ashx',
                    type: 'POST',
                    data: param,
                    async: false,
                    success: function (data) {
                        alert(data);
                    }
                });
            }
        </script>

    8、由于【数值】跟【备注】两栏均要保存,所以调用.find('.colControl')全部传过去,接着,看一下【UpdateBaseSetupColValue.ashx】的代码吧:

    <%@ WebHandler Language="C#" Class="UpdateBaseSetupColValue" %>
    
    using System;
    using System.Web;
    using System.Collections.Generic;
    
    
    public class UpdateBaseSetupColValue : IHttpHandler
    {
        
        public void ProcessRequest (HttpContext context) {
            context.Response.ContentType = "text/plain";
            //context.Response.Write("Hello World");
    
    
            var req = context.Request;
            context.Response.Write(SaveColValue(req));
        }
     
        public bool IsReusable {
            get {
                return false;
            }
        }
    
    
        /// <summary>
        /// 保存欄位值
        /// </summary>
        /// <returns></returns>
        private string SaveColValue(HttpRequest reqForm)
        {
            var req = reqForm.Form;
            var action = req["Action"];
            var _colValue = "colValue_";
            var _colDesction = "colDesction_";
            if (!string.IsNullOrEmpty(action) && action == "Save")
            {
                List<String> listSql = new List<string>();
                foreach (var item in req.AllKeys)
                {
                    if (item.IndexOf(_colValue) > -1)
                    {
                        listSql.Add(string.Format("UPDATE [CWNS_BaseSetUp_Tab] SET [colvalue] =N'{0}' WHERE ID='{1}'",
                                                  req[item], item.Replace(_colValue, "")));
                    }
                    else if (item.IndexOf(_colDesction) > -1)
                    {
                        listSql.Add(string.Format("UPDATE [CWNS_BaseSetUp_Tab] SET [colDesction] =N'{0}' WHERE ID='{1}'",
                                                  req[item], item.Replace(_colDesction, "")));
                    }
                }
                try
                {
                    DbHelperSQL.ExecuteSqlTran(listSql);
                    return "保存成功!";
                }
                catch (Exception)
                {
                    return "保存失敗!";
                }
                
                //Response.Redirect(Request.Url.ToString());
            }
            return "參數缺失,請聯系管理員!";
        }
    }

    这样子,就实现了动态保存用户所作的修改了。当然,就算用户没修改,也会重新update一次所有的数据,这点需要注意,嘻嘻。

    虽然过程没有细说,但该说的全都有写了,如果感兴趣的话,不妨花点时间仔细阅读一下。

    补充一下css文件吧,也挺不错的,后面我还会单独写一篇出来分享一下:

    /*-- 表格樣式 --*/
    .tbinfo{background: #d6e0ef; line-height: 18px;
        width: 100%;
    }
    .tbinfo th{font-size:12px;background-color:#97CBFF;border-bottom:1px solid #a5ceef; text-align:center;color:    #003399;}
    .tbinfo td{background: #fff;padding:2px 0;}
    .tbinfo .lt{background: #fafafa;text-align: right; padding:0 4px; width:15%; white-space:nowrap;}
    .tbinfo .rt{background: #fff; text-align:left; padding:0 2px;}
    .tbinfo .rt:hover{background: #fafafa;}
    .hidden { display:none;}
    
    /*-- 頁碼樣式 --*/
    .page
    {
        text-align:center;
        height:26px;
    }
    
    .page a
    {
        padding:2px 6px 2px 6px;
        width:24px;
        border:1px solid blue;
        text-align:center;
        font-size:12px;
        line-height:20px;
    }
    
    .page a:hover
    {
        padding:2px 6px 2px 6px;
        width:24px;
        border:1px solid red;
        text-align:center;
        font-size:12px;
        line-height:20px;
    }
    
    .page span
    {
        padding:2px 6px 2px 6px;
        width:24px;
        border:1px solid silver;
        text-align:center;
        font-size:12px;
        line-height:20px;
        color:silver;
    }
  • 相关阅读:
    Eular质数筛法
    质数测试
    求树的直径
    常用排序的实现方法(数据结构)
    关于整数的整数因子和问题的若干研究(数学)
    状态压缩中常用的位运算(DP)
    舞蹈链--求精密覆盖(数据结构)
    高斯消元模板,整数(数学)
    树状数组 (数据结构)
    二叉树还原--通用类型模板类(数据结构)
  • 原文地址:https://www.cnblogs.com/seasons1987/p/3274516.html
Copyright © 2020-2023  润新知