ASP.NET 动态列表视图 Web 应用程序

Posted

技术标签:

【中文标题】ASP.NET 动态列表视图 Web 应用程序【英文标题】:ASP.NET Dynamic Listview web application 【发布时间】:2015-01-20 14:55:21 【问题描述】:

我有几个 sqlserver 表,每个表都代表一个应用程序。 我需要维护(查看/编辑/插入/删除记录)所有这些表。 所有这些应用程序表都有一个名为 ID 的 int 主键列。

为了完成这项任务,我创建了一些 SqlServer 配置表,这些配置表是构建页面以维护这些应用程序表的基础。

dbo.ApplGenerator_Applications: 此表将应用程序映射到具有额外字段的真实 SqlServer 表,以便在 Web 应用程序的视图窗格中对数据进行排序。

CREATE TABLE [dbo].[ApplGenerator_Applications](
    [ApplicationName] [varchar](50) NOT NULL,
    [RealTable] [varchar](255) NOT NULL,
    [OrderBy] [varchar](255) NOT NULL,
    [Desc_OrderBy] [varchar](255) NOT NULL
)

由于主键始终具有相同的名称和类型,因此我不需要在应用程序配置表中添加该信息。

ApplGenerator_Master: 该表是以下内容的基础: • 构建具有搜索功能的标题 • 构建列表视图列 • 构建查询以检索数据

CREATE TABLE [dbo].[ApplGenerator_Master](
    [ApplicationName] [varchar](50) NOT NULL,
    [FieldId] [varchar](50) NOT NULL,
    [FieldTitle] [varchar](50) NULL,
    [FieldName] [varchar](255) NULL,
    [FieldAlign] [varchar](50) NULL,
    [FieldWidth] [varchar](50) NULL,
    [Position] [int] NULL
)

结合起来,这两个配置表是构建列表视图对象(过滤器和数据)和填充数据列表视图的基础。

Master.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Master.aspx.cs" Inherits="ApplicationGenerator.Master" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <link href="/Styles/StyleSheet.css" rel="stylesheet" type="text/css" />
    <script src="/Scripts/Script.js" type="text/javascript"></script>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <ajax:ToolkitScriptManager ID="MasterScriptManager" runat="server"></ajax:ToolkitScriptManager>
        <script type="text/javascript">
            document.body.onload = function ()  resizeContent('pageContent'); 
            document.body.onresize = function ()  resizeContent('pageContent'); 
        </script>
        <asp:UpdatePanel ID="myUpdatePanel" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true">
        <ContentTemplate>
            <asp:DataPager ID="Master_Data_DataPager" runat="server"
                PagedControlID="Master_Data_ListView"
                PageSize="50">
                <Fields>
                    <asp:NextPreviousPagerField ButtonType="Image"
                                                FirstPageImageUrl="/Images/DataPager/first.png"
                                                NextPageImageUrl="/Images/DataPager/next.png"
                                                PreviousPageImageUrl="/Images/DataPager/previous.png"
                                                LastPageImageUrl="/Images/DataPager/last.png"
                                                ShowFirstPageButton="True"
                                                ShowNextPageButton="False" />
                    <asp:NumericPagerField />
                    <asp:NextPreviousPagerField ButtonType="Image"
                                                FirstPageImageUrl="/Images/DataPager/first.png"
                                                NextPageImageUrl="/Images/DataPager/next.png"
                                                PreviousPageImageUrl="/Images/DataPager/previous.png"
                                                LastPageImageUrl="/Images/DataPager/last.png"
                                                ShowLastPageButton="True"
                                                ShowPreviousPageButton="False" />
                </Fields>
            </asp:DataPager>
            <asp:ListView ID="Master_Filter_ListView" runat="server">
            </asp:ListView>
            <div id="pageContent" style="overflow:auto;">
                <asp:ListView ID="Master_Data_ListView" runat="server"
                    DataKeyNames="ID" DataSourceID="Master_Data_SqlDataSource"
                    OnPagePropertiesChanging="Master_Data_ListView_PagePropertiesChanging">
                </asp:ListView>
                <asp:SqlDataSource ID="Master_Data_SqlDataSource" runat="server"
                    ConnectionString="<%$ ConnectionStrings:ApplicationServices %>"
                    SelectCommand="dbo.ApplGenerator_Master_Data_GetList" SelectCommandType="StoredProcedure"
                    DeleteCommand="dbo.ApplGenerator_Master_DeleteRecord" DeleteCommandType="StoredProcedure"
                    OnSelecting="ApplicationUsersSqlDataSource_Selecting"
                    OnDeleting="ApplicationUsersSqlDataSource_Deleting">
                    <DeleteParameters>
                        <asp:Parameter Direction="Input" Name="ID" />
                    </DeleteParameters>
                </asp:SqlDataSource>
            </div>
        </ContentTemplate>
        </asp:UpdatePanel>
    </form>
</body>
</html>

Master.aspx.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace ApplicationGenerator

    public partial class Master : System.Web.UI.Page
    
        private static string sConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString();
        private static string sApplication = "";

        private static DataTable dtApplication = null;
        private static DataTable dtFilter = null;

        public struct ExternalReferencesStruct
        
            public ListView DataListView;
        

        public class myClass
        
            private ExternalReferencesStruct classObjs;

            public myClass(ExternalReferencesStruct paramObjs)
            
                classObjs = paramObjs;
            
        

        protected void Page_Init(object sender, EventArgs e)
        
            sApplication = Request.QueryString["application"];

            dtApplication = ApplicationGenerator_Application_Get();
            dtFilter = ApplicationGenerator_Master_Filter_GetList();

            Build_MasterFilterListView();
            Build_MasterDataListView();

            Master_Filter_ListView.DataBind();
        

        protected void Page_Load(object sender, EventArgs e)
        
            //if (!this.Page.IsPostBack)
            //
                Master_Data_ListView.DataBind();
            //
            string scriptString = "<script LANGUAGE='javascript'>resizeContent('pageContent');</script>";
            ScriptManager.RegisterStartupScript(this, this.GetType(), "myScript_Load", scriptString, false);
        

        #region Master_Filtro_ListView
        public void Build_MasterFilterListView()
        
            ExternalReferencesStruct ExternalObjs = new ExternalReferencesStruct();
            ExternalObjs.DataListView = Master_Data_ListView;

            Master_Filter_ListView.LayoutTemplate = new MasterFilterLayoutTemplate(ExternalObjs);
            Master_Filter_ListView.ItemTemplate = new MasterFilterItemTemplate();
            Master_Filter_ListView.EmptyDataTemplate = new MasterFilterLayoutTemplate(ExternalObjs);
        

        public class MasterFilterLayoutTemplate : myClass, ITemplate
        
            ExternalReferencesStruct ExternalReferences = new ExternalReferencesStruct();
            public MasterFilterLayoutTemplate(ExternalReferencesStruct paramExternalReferences)
                : base(paramExternalReferences)
            
                ExternalReferences = paramExternalReferences;
            

            protected void ApplyFilter_Click(object sender, ImageClickEventArgs e)
            
                ExternalReferences.DataListView.DataBind();
            

            public void InstantiateIn(System.Web.UI.Control container)
            
                HtmlTable myTable = new HtmlTable();
                myTable.Width = "100%";
                myTable.Border = 0;
                myTable.CellPadding = 0;
                myTable.CellSpacing = 0;
                myTable.Style.Add("table-layout", "fixed");

                HtmlTableRow row = null;
                HtmlTableRow rowF = null;
                HtmlTableCell cell = null;
                TextBox tbFiltro = null;

                row = new HtmlTableRow();
                rowF = new HtmlTableRow();
                row.ID = "Row_Names";
                rowF.ID = "Row_Filters";

                ImageButton ib = null;

                //New Record
                cell = new HtmlTableCell();
                cell.Width = "20px";
                cell.Align = "center";
                    ib = new ImageButton();
                    ib.ID = "NewRecImageButton";
                    ib.ImageUrl = "/Images/Applications/New.png";
                    ib.ToolTip = "New Record";
                    ib.OnClientClick = "javascript:ViewEditDetail('" + sApplication + "', '-1');return false;";
                    cell.Controls.Add(ib);
                row.Cells.Add(cell);

                //Filter
                cell = new HtmlTableCell();
                cell.Width = "20px";
                cell.Align = "center";
                ib = new ImageButton();
                ib.ID = "FilterImageButton";
                ib.ImageUrl = "/Images/Applications/Filter.png";
                ib.ToolTip = "Apply Filtro";
                ib.Click += new ImageClickEventHandler(ApplyFilter_Click);
                cell.Controls.Add(ib);
                rowF.Cells.Add(cell);

                //Field Names
                foreach (DataRow dtrow in dtFilter.Rows)
                
                    //Header - Field Titles
                    cell = new HtmlTableCell();
                    cell.Width = dtrow["FieldWidth"].ToString();
                    cell.Align = "center";
                    cell.Style.Add("font-weight", "bold");
                    cell.Controls.Add(new LiteralControl(dtrow["FieldTitle"].ToString()));
                    row.Cells.Add(cell);

                    //Header - Filter TextBoxes
                    cell = new HtmlTableCell();
                    cell.Width = dtrow["FieldWidth"].ToString();
                    tbFiltro = new TextBox();
                    tbFiltro.ID = dtrow["FieldId"].ToString();
                    tbFiltro.Width = new Unit("99%");
                    cell.Controls.Add(tbFiltro);
                    rowF.Cells.Add(cell);
                
                myTable.Rows.Add(row);
                myTable.Rows.Add(rowF);

                //Container para Items
                row = new HtmlTableRow();
                row.ID = "itemPlaceholder";
                myTable.Rows.Add(row);

                container.Controls.Add(myTable);
            
        

        public class MasterFilterItemTemplate : ITemplate
        
            public void InstantiateIn(System.Web.UI.Control container)
            
            
        
        #endregion

        #region Master_Data_ListView
        public void Build_MasterDataListView()
        
            ExternalReferencesStruct ExternalObjs = new ExternalReferencesStruct();
            ExternalObjs.DataListView = Master_Data_ListView;

            Master_Data_ListView.LayoutTemplate = new MasterDataLayoutTemplate(ExternalObjs);
            Master_Data_ListView.ItemTemplate = new MasterDataItemTemplate(ExternalObjs);
            Master_Data_ListView.EmptyDataTemplate = new MasterDataLayoutTemplate(ExternalObjs);
        

        public class MasterDataLayoutTemplate : myClass, ITemplate
        
            ExternalReferencesStruct ExternalReferences = new ExternalReferencesStruct();
            public MasterDataLayoutTemplate(ExternalReferencesStruct paramExternalReferences)
                : base(paramExternalReferences)
            
                ExternalReferences = paramExternalReferences;
            

            public void InstantiateIn(System.Web.UI.Control container)
            
                HtmlTable myTable = new HtmlTable();
                myTable.Width = "100%";
                myTable.Border = 0;
                myTable.CellPadding = 0;
                myTable.CellSpacing = 0;
                myTable.Style.Add("table-layout", "fixed");

                HtmlTableRow row = null;
                HtmlTableCell cell = null;

                row = new HtmlTableRow();

                //Button Delete
                cell = new HtmlTableCell();
                cell.Width = "20px";
                cell.Align = "center";
                row.Cells.Add(cell);

                //Field Names
                foreach (DataRow dtrow in dtFilter.Rows)
                
                    //Header - Field Names
                    cell = new HtmlTableCell();
                    cell.Width = dtrow["FieldWidth"].ToString();
                    row.Cells.Add(cell);
                
                myTable.Rows.Add(row);

                //Item Container
                row = new HtmlTableRow();
                row.ID = "itemPlaceholder";
                myTable.Rows.Add(row);

                container.Controls.Add(myTable);
            
        

        public class MasterDataItemTemplate : myClass, ITemplate
        
            ExternalReferencesStruct ExternalReferences = new ExternalReferencesStruct();
            public MasterDataItemTemplate(ExternalReferencesStruct paramExternalReferences)
                : base(paramExternalReferences)
            
                ExternalReferences = paramExternalReferences;
            

            public void InstantiateIn(System.Web.UI.Control container)
            
                HtmlTableRow row = new HtmlTableRow();

                row.DataBinding += new EventHandler(row_DataBinding);

                DataRowView dataRowView = ((ListViewDataItem)container).DataItem as DataRowView;
                if (dataRowView != null)
                
                    string sPK = dataRowView[0].ToString();
                    row.Attributes.Add("onclick", "ViewEditDetail('" + sApplication + "', '" + sPK + "');");
                    row.Attributes.Add("onmouseout", "MouseOut(this);");
                    row.Attributes.Add("onmouseover", "MouseOver(this);");
                    row.Attributes.Add("title", "View/Edit Details");
                    row.Style.Add("cursor", "pointer");
                
                container.Controls.Add(row);
            

            protected void row_DataBinding(object sender, EventArgs e)
            
                HtmlTableRow row = (HtmlTableRow)sender;
                DataRowView dataRowView = ((ListViewDataItem)row.NamingContainer).DataItem as DataRowView;
                string sPK = dataRowView[0].ToString();

                HtmlTableCell cell = null;
                ImageButton ib = null;

                //Button Delete
                cell = new HtmlTableCell();
                cell.Width = "20px";
                cell.Align = "center";
                ib = new ImageButton();
                ib.ID = "DelImageButton";
                ib.CommandName = "Delete";
                ib.ImageUrl = "/Images/Applications/Delete.png";
                ib.ToolTip = "Delete Record";
                ib.OnClientClick = "javascript:return myConfirm('Proceed with Record Elimination?');";
                cell.Controls.Add(ib);
                row.Controls.Add(cell);

                int i = 1;
                foreach (DataRow dtrow in dtFilter.Rows)
                
                    cell = new HtmlTableCell();
                    cell.Width = dtrow["FieldWidth"].ToString();
                    Literal MyLiteral = new Literal();
                    MyLiteral.Text = dataRowView[i++].ToString();

                    cell.Controls.Add(MyLiteral);
                    row.Controls.Add(cell);
                
            
        
        #endregion

        #region Data Functions
        private static DataTable ApplicationGenerator_Application_Get()
        
            string sStrSP = "";

            SqlConnection conn = null;
            SqlCommand cmd = null;
            SqlDataAdapter da = null;
            DataSet ds = null;

            sStrSP = "dbo.ApplGenerator_Application_Get";

            conn = new SqlConnection(sConnectionString);
            cmd = new SqlCommand();
            ds = new DataSet();
            cmd.Connection = conn;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = sStrSP;
            cmd.Parameters.Add(new SqlParameter("@ApplicationName", sApplication));

            conn.Open();
            da = new SqlDataAdapter(cmd);
            da.Fill(ds);

            DataTable dt = ds.Tables[0];

            cmd.Dispose();
            da.Dispose();
            ds.Dispose();
            conn.Close();

            return dt;
        

        private static DataTable ApplicationGenerator_Master_Filter_GetList()
        
            string sStrSP = "";

            SqlConnection conn = null;
            SqlCommand cmd = null;
            SqlDataAdapter da = null;
            DataSet ds = null;

            sStrSP = "dbo.ApplGenerator_Master_Filter_GetList";

            conn = new SqlConnection(sConnectionString);
            cmd = new SqlCommand();
            ds = new DataSet();
            cmd.Connection = conn;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = sStrSP;
            cmd.Parameters.Add(new SqlParameter("@ApplicationName", sApplication));

            conn.Open();
            da = new SqlDataAdapter(cmd);
            da.Fill(ds);

            DataTable dt = ds.Tables[0];

            cmd.Dispose();
            da.Dispose();
            ds.Dispose();
            conn.Close();

            return dt;
        

        private static DataTable ApplicationGenerator_Master_Data_GetList(ListView FilterListView)
        
            DataTable dtWhere = new DataTable();
            dtWhere.Clear();
            dtWhere.Columns.Add("FieldId");
            dtWhere.Columns.Add("FieldText");

            string sFilterId = "";
            string sFilterText = "";
            TextBox tbFilter = null;
            foreach (DataRow dtrow in dtFilter.Rows)
            
                sFilterId = dtrow["FieldId"].ToString();
                tbFilter = (TextBox)FilterListView.Controls[0].FindControl(sFilterId);
                if (tbFilter != null)
                
                    sFilterText = tbFilter.Text;
                    if (sFilterText != "")
                    
                        DataRow dtWhereRow = dtWhere.NewRow();
                        dtWhereRow["FieldId"] = sFilterId;
                        dtWhereRow["FieldText"] = sFilterText;
                        dtWhere.Rows.Add(dtWhereRow);
                    
                
            

            DataTable dt = new DataTable();

            SqlConnection conn = new SqlConnection(sConnectionString);
            SqlCommand cmd = null;
            conn.Open();

            try
            
                string sStrSP = "dbo.ApplGenerator_Master_Data_GetList";
                cmd = new SqlCommand(sStrSP, conn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add(new SqlParameter("@ApplicationName", sApplication));
                cmd.Parameters.Add(new SqlParameter("@dtWhere", dtWhere));

                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                adapter.Fill(dt);
            
            finally
            
                cmd.Dispose();
                if (conn != null)
                    conn.Close();
            

            return dt;
        
        #endregion

        #region Master_Data_ListView
        protected virtual void Master_Data_ListView_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
        
            string scriptString = "";

            Master_Data_DataPager.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
            Master_Data_ListView.DataBind();

            scriptString = "<script LANGUAGE='javascript'>resizeContent('pageContent');</script>";
            ScriptManager.RegisterStartupScript(this, this.GetType(), "myScript_PageChanging", scriptString, false);
        
        #endregion

        #region Master_Data_SqlDataSource
        protected void ApplicationUsersSqlDataSource_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
        
            DataTable dtWhere = new DataTable();
            dtWhere.Clear();
            dtWhere.Columns.Add("FieldId");
            dtWhere.Columns.Add("FieldText");

            string sFilterId = "";
            string sFilterText = "";
            TextBox tbFilter = null;
            foreach (DataRow dtrow in dtFilter.Rows)
            
                sFilterId = dtrow["FieldId"].ToString();
                tbFilter = (TextBox)Master_Filter_ListView.Controls[0].FindControl(sFilterId);
                if (tbFilter != null)
                
                    sFilterText = tbFilter.Text;
                    if (sFilterText != "")
                    
                        DataRow dtWhereRow = dtWhere.NewRow();
                        dtWhereRow["FieldId"] = sFilterId;
                        dtWhereRow["FieldText"] = sFilterText;
                        dtWhere.Rows.Add(dtWhereRow);
                    
                
            

            SqlParameter Param_Aplicacao = new SqlParameter("@ApplicationName", sApplication)
            
                Direction = ParameterDirection.Input
            ;

            SqlParameter Param_dtwhere = new SqlParameter("@dtWhere", dtWhere)
            
                Direction = ParameterDirection.Input
            ;

            e.Command.Parameters.Add(Param_Aplicacao);
            e.Command.Parameters.Add(Param_dtwhere);
        

        protected void ApplicationUsersSqlDataSource_Deleting(object sender, SqlDataSourceCommandEventArgs e)
        
            SqlParameter Param_Aplicacao = new SqlParameter("@ApplicationName", sApplication)
            
                Direction = ParameterDirection.Input
            ;

            e.Command.Parameters.Add(Param_Aplicacao);
        
        #endregion
    

应用程序几乎准备就绪,寻呼机工作正常 新的和过滤器按钮(过滤器 ListView 中的控件)按预期工作。

问题是当我单击图标删除一行时(数据ListView ItemTemplate中的ImageButton控件),删除的代码都没有运行,数据列表视图也没有重新加载。

Sourcecode VisualStudio2010

SqlServer2012 backup

我是 ASP.NET 的新手,我肯定做错了(非常)错误。 我对如何解决这个问题没有想法。 有人可以帮忙吗?

谢谢,

马里奥·努内斯

【问题讨论】:

这个问题有点完整了,你能删除与问题无关的代码吗?我发现很难滚动浏览所有内容。 【参考方案1】:

您正在ListView 中动态创建控件,问题是在 PostBack 上这些控件丢失(它们的事件也是如此),因为数据尚未重新绑定。

快试试这个,看看能不能解决:

protected void Page_Load(object sender, EventArgs e)

    //if (!this.Page.IsPostBack)
    //
        Master_Data_ListView.DataBind();
    //

编辑:

没关系,我看错了标签! :o

【讨论】:

感谢您的回复。现在 ListView 重新加载,但 SqlDataSource 删除事件不会触发。 再次感谢您的宝贵时间。我放回了 C# 代码。过滤器 ListView 具有与数据 ListView 不同的数据源。 Filter ListView 充当标题(标题和过滤器文本框),dataListView 显示真实数据。 哎呀我当时完全看错了标签。你的按钮看起来不错,你在Page_Init 中得到了Master_Filter_ListView.DataBind(); 并不是说​​这很糟糕,但是在第一次加载时,你现在可以双重绑定到控件,因为我们已经更改了Page_Load。现在,如果您将Build_MasterDataListView(); 放入Page_Load,您的事件现在应该可以正常触发了。 再次感谢您的宝贵时间。 Page_Init: Master_Filter_ListView.DataBind(); Page_Load: Master_Data_ListView.DataBind();第一次:删除行并重新加载确定。如果我们继续删除,也没关系。当在 DataPager 中更改页面或使用 FilterImageButton 应用过滤器(在过滤器 ListView 中)然后重新加载列表视图但从不调用 SqlDataSource 删除事件。从上周开始我就遇到了这个问题。我尝试了几种不同的方法(有些非常愚蠢)来绕过这个问题,但到目前为止都没有。 我认为您的问题是您将事件附加到代码中。由于这一切都是动态创建的,因此在 PostBack 上必须重新附加数据和事件,以便 .NET 在触发它们之前将它们重新拾取。事件在Page_Load 之后触发,因此使用DataPager 和其他此类事情可能会导致您的动态附加事件被丢弃。我认为您需要查看需要重新运行“Build_MasterDataListView();”的位置在某些事件上。

以上是关于ASP.NET 动态列表视图 Web 应用程序的主要内容,如果未能解决你的问题,请参考以下文章

动态网页的工作机制——Asp.net 运行机制

在 ASP.NET MVC 中从部分视图发布动态表单数据

ASP.NET MVC 中单独程序集中的视图

在 ASP.NET MVC Web 应用程序中包含预编译的视图

ASP.NET Web 应用程序的 FxCop 规则列表子集

浅谈Asp.net 运行机制