【问题标题】:Displaying specific information on aspx page using database使用数据库在 aspx 页面上显示特定信息
【发布时间】:2015-06-04 11:57:04
【问题描述】:

我正在使用 ASP.NET Web 窗体和 SQL 数据库构建一个网站。

在一个特定页面上,我有许多带有一些信息的房屋。
共有571间房屋。
当我点击一个特定的房子时,我想打开一个新页面,其中包含有关该房子的更多信息。
所有数据都来自数据库中的一个表。

有没有办法知道选择了哪所房子,并在该房子的新 aspx 页面上显示数据?

我知道我可以为每个房子创建许多单独的 aspx 页面,但是有 571 个房子,并且必须有 571 个 aspx 页面。那是太多浪费的代码了。
当我单击房屋名称时,我只想要一个 aspx 页面,但我希望它知道我已选择该房屋并显示该特定房屋的信息。就像它访问那所房子的数据库信息并显示它一样。

这里的主要障碍是知道选择了什么房子。我知道如何显示数据库中的信息。

Houses.aspx

当我点击房屋名称时,我想显示如下页面。

HouseInfo.aspx

HouseInfo.aspx.cs

using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
            {
                using (SqlCommand command = new SqlCommand("SELECT Id, Name, Townland, Near, Status, Built, Description, Families FROM Houses ORDER BY Name DESC", connection))
                {
                    connection.Open();
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            lblId.Text = reader[0].ToString();
                            lblName.Text = reader[1].ToString();
                            lblTown.Text = reader[2].ToString();
                            lblNear.Text = reader[3].ToString();
                            lblStatus.Text = reader[4].ToString();
                            lblBuilt.Text = reader[5].ToString();
                            lblDesc.Text = reader[6].ToString();
                            lblFam.Text = reader[7].ToString();
                        }
                    }
                }
            }   
        }

这就是我访问数据库以在 HouseInfo 页面上显示一些信息的方式。

HouseInfo.aspx

<b>ID:</b> <asp:Label ID="lblId" runat="server"></asp:Label>
<br /><b>Name of House:</b> <asp:Label ID="lblName" runat="server"></asp:Label>
<br /><b>Townland:</b> <asp:Label ID="lblTown" runat="server"></asp:Label>
<br /><b>Near:</b> <asp:Label ID="lblNear" runat="server"></asp:Label>
<br /><b>Status/Public Access:</b> <asp:Label ID="lblStatus" runat="server </asp:Label>
<br /><b>Date Built:</b> <asp:Label ID="lblBuilt" runat="server"></asp:Label>
<br /><b>Description:</b> <asp:Label ID="lblDesc" runat="server"></asp:Label>
<br /><b>Associated Families:</b> <asp:Label ID="lblFam" runat="server"></asp:Label>

Houses.aspx

<%@ Page Title="Houses" Language="C#" MasterPageFile="~/Master.Master" AutoEventWireup="true" CodeBehind="Houses.aspx.cs" Inherits="Houses_of_Mayo.images.Houses" EnableEventValidation="false" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

    <script>
        $(function () { setCurrentTab('tab2'); });
    </script>
    <div class="box">
        <div>
            <div class="body">
                <h1>Houses</h1>

                <ul id="rooms">
                    <asp:Repeater ID="rptData" runat="server" >
                        <ItemTemplate>
                            <li>
                                <a href="HouseInfo.aspx">
                                    <img src="x" alt="img" /></a>
                                <h2>
                                    <a href="HouseInfo.aspx"><asp:Label runat="server" Text='<%# Eval("Name") %>'></asp:Label></a></h2>
                                <p>
                                    <b>ID: </b>
                                    <asp:Label runat="server" Text='<%# Eval("Id") %>'></asp:Label>
                                    <br />
                                    <b>Name of House: </b>
                                    <asp:Label runat="server" Text='<%# Eval("Name") %>'></asp:Label>
                                    <br />
                                    <b>Townland: </b>
                                    <asp:Label runat="server" Text='<%# Eval("Townland") %>'></asp:Label>
                                    <br />
                                    <b>Near: </b>
                                    <asp:Label runat="server" Text='<%# Eval("Near") %>'></asp:Label>
                                    <br />
                                    <b>Status/Public Access: </b>
                                    <asp:Label runat="server" Text='<%# Eval("Status") %>'></asp:Label>
                                    <br />

                                    <b>Date Built: </b>
                                    <asp:Label runat="server" Text='<%# Eval("Built") %>'></asp:Label>
                                </p>
                            </li>
                        </ItemTemplate>
                    </asp:Repeater>
                </ul>
                <asp:Repeater ID="rptPager" runat="server">
    <ItemTemplate>
        <asp:LinkButton ID="lnkPage" runat="server" Text='<%#Eval("Text") %>' CommandArgument='<%# Eval("Value") %>'
            style="padding:8px; margin:2px; background:#ac9e94; border:solid 1px #666; font:8pt; color:#594334; display: inline-block;"
            CssClass='<%# Convert.ToBoolean(Eval("Enabled")) ? "page_enabled" : "page_disabled" %>'
            OnClick="Page_Changed" OnClientClick='<%# !Convert.ToBoolean(Eval("Enabled")) ? "return false;" : "" %>'></asp:LinkButton>
   </ItemTemplate>
</asp:Repeater>
            </div>
        </div>  
    </div>
</asp:Content>

Houses.aspx.cs

private int PageSize = 5;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.GetCustomersPageWise(1);
            }
        }

        private void GetCustomersPageWise(int pageIndex)
        {
            string constring = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constring))
            {
                using (SqlCommand cmd = new SqlCommand("GetHousesPageWise", con))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@PageIndex", pageIndex);
                    cmd.Parameters.AddWithValue("@PageSize", PageSize);
                    cmd.Parameters.Add("@RecordCount", SqlDbType.Int, 4);
                    cmd.Parameters["@RecordCount"].Direction = ParameterDirection.Output;
                    con.Open();
                    IDataReader idr = cmd.ExecuteReader();
                    rptData.DataSource = idr;
                    rptData.DataBind();
                    idr.Close();
                    con.Close();
                    int recordCount = Convert.ToInt32(cmd.Parameters["@RecordCount"].Value);
                    this.PopulatePager(recordCount, pageIndex);
                }
            }
        }

        private void PopulatePager(int recordCount, int currentPage) 
        {
            double dblPageCount = (double)((decimal)recordCount / Convert.ToDecimal(PageSize));
            int pageCount = (int)Math.Ceiling(dblPageCount);
            List<ListItem> pages = new List<ListItem>();
            if (pageCount > 0)
            {
                for (int i = 1; i <= pageCount; i++)
                {
                    pages.Add(new ListItem(i.ToString(), i.ToString(), i != currentPage));
                }
            }
            rptPager.DataSource = pages;
            rptPager.DataBind();
        }

        protected void Page_Changed(object sender, EventArgs e)
        {
            int pageIndex = int.Parse((sender as LinkButton).CommandArgument);
            this.GetCustomersPageWise(pageIndex);
        }

地图 (HouseInfo.aspx)

HouseInfo.aspx

<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
    <script>
        function initialize() {
            var myLatlng = new google.maps.LatLng(53.613873, -9.668301);
            var mapOptions = {
                zoom: 17,
                center: myLatlng
            }
            var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

            var contentString = '<div id="content">' +
                                  '<div id="siteNotice">' +
                                  '</div>' +
                                  '<h2 id="firstHeading" class="firstHeading">Aasleagh Lodge</h2>' +
                                  '<div id="bodyContent">' +
                                  '<b>ID:</b> A1' +
                                  '</br><b>Name:</b> Aasleagh Lodge' +
                                  '</br><b>Townland:</b> Srahatloe' +
                                  '</br><b>Ref:</b> 1' +
                                  '</br><b>Latitude:</b> 53.613873' +
                                  '</br><b>Longitude:</b> -9.668301' +
                                  '</div>' +
                                  '</div>';

            var infowindow = new google.maps.InfoWindow({
                content: contentString
            });

            var image = 'Images/icon56.png';
            var marker = new google.maps.Marker({
                position: myLatlng,
                map: map,
                title: 'Aasleagh Lodge',
                icon: image
            });
            google.maps.event.addListener(marker, 'click', function () {
                infowindow.open(map, marker);
            });
        }

        google.maps.event.addDomListener(window, 'load', initialize);

房屋信息表

[Id]       CHAR (10)      NOT NULL,
    [Name]     NVARCHAR (MAX) NULL,
    [Townland] NVARCHAR (MAX) NULL,
    [Ref]      INT            NULL,
    [Lat]      FLOAT (53)     NULL,
    [Lng]      FLOAT (53)     NULL,
    CONSTRAINT [PK_HouseInfo] PRIMARY KEY CLUSTERED ([Id] ASC)

【问题讨论】:

  • lblId 有你正在查看的房子的 id 吗?
  • 向我们展示您的 Houses.aspx.cs,这样我也可以添加该部分来回答
  • 嗨!我已经编辑了你的问题,所以你需要什么更清楚。
  • 我需要你的Houses.aspx.cs,你的问题很清楚,不需要解释。只需将您的 Houses.aspx.cs 和 Houses.aspx 代码粘贴到您的问题中,就像您为 HouseInfo 所做的那样
  • 已发布 Houses.aspx 和 Houses.aspx.cs

标签: c# asp.net webforms


【解决方案1】:

有多种方法可以做到这一点。最好 (IMO) 和最简单的方法是使用查询字符串将所选房屋的 ID(或主键数据)传递给下一个 Web 表单并使用该值显示数据。

【讨论】:

    【解决方案2】:

    在此代码中,您将房屋 ID 发送到其他页面。

    <a href='<%# "HouseInfo.aspx?HouseId=" + Eval("Id").ToString() %>'>
                        <img src="x" alt="img" /></a>
    

    在这里,您将获得该 ID

    string HouseId = Request.Params["HouseId"].ToString();
    

    您也在此处过滤数据以仅获取房屋信息

    "SELECT Id, Name, Townland, Near, Status, Built, Description, Families FROM Houses WHERE Id = '" + HouseId + "' ORDER BY Name DESC"
    

    完整代码;

    HouseInfo.aspx.cs

    string HouseId = Request.Params["HouseId"].ToString();
    
    using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
    {
        using (SqlCommand command = new SqlCommand("SELECT Id, Name, Townland, Near, Status, Built, Description, Families FROM Houses WHERE Id = '" + HouseId + "' ORDER BY Name DESC", connection))
        {
             connection.Open();
             using (SqlDataReader reader = command.ExecuteReader())
             {
                  while (reader.Read())
                  {
                      lblId.Text = reader[0].ToString();
                      lblName.Text = reader[1].ToString();
                      lblTown.Text = reader[2].ToString();
                      lblNear.Text = reader[3].ToString();
                      lblStatus.Text = reader[4].ToString();
                      lblBuilt.Text = reader[5].ToString();
                      lblDesc.Text = reader[6].ToString();
                      lblFam.Text = reader[7].ToString();
                  }
             }
        }
    }   
    

    Houses.aspx

    <ul id="rooms">
        <asp:Repeater ID="rptData" runat="server" >
            <ItemTemplate>
                <li>
                    <a href='<%# "HouseInfo.aspx?HouseId=" + Eval("Id").ToString() %>'>
                    <img src="x" alt="img" /></a>
                    <h2>
                    <a href='<%# "HouseInfo.aspx?HouseId=" + Eval("Id").ToString() %>'><asp:Label runat="server" Text='<%# Eval("Name") %>'></asp:Label></a></h2>
                     <p>
                     <b>ID: </b>
                     <asp:Label runat="server" Text='<%# Eval("Id") %>'></asp:Label>
                     <br />
                     <b>Name of House: </b>
                     <asp:Label runat="server" Text='<%# Eval("Name") %>'></asp:Label>
                     <br />
                     <b>Townland: </b>
                     <asp:Label runat="server" Text='<%# Eval("Townland") %>'></asp:Label>
                     <br />
                     <b>Near: </b>
                     <asp:Label runat="server" Text='<%# Eval("Near") %>'></asp:Label>
                     <br />
                     <b>Status/Public Access: </b>
                     <asp:Label runat="server" Text='<%# Eval("Status") %>'></asp:Label>
                     <br />
    
                     <b>Date Built: </b>
                     <asp:Label runat="server" Text='<%# Eval("Built") %>'></asp:Label>
                     </p>
                 </li>
            </ItemTemplate>
        </asp:Repeater>
    </ul>
    

    【讨论】:

    • 这并没有完全回答问题(他不知道如何将参数传递给其他页面),并且容易发生SQL注入。
    • @cosmo0 如果您愿意阅读 cmets,我正在等待他的 Houses.aspx.cs 代码来完成该部分。
    • 已发布 Houses.aspx 和 Houses.aspx.cs
    • int HouseId = Convert.ToInt32(Request.Params["HouseId"]);附加信息:输入字符串的格式不正确。注意:ID 是一个字符,因为它包含字母和数字
    • 使用 (SqlDataReader reader = command.ExecuteReader()) 附加信息:列名“A1”无效。 'A1' 是 ID
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-05
    • 2020-10-20
    相关资源
    最近更新 更多