从母版页 selectedItems 获取子页数据

Get child page data from master page selectedItems

我的母版页中有位置 DropdownList。我在我的子页面中设置了控件,该控件从母版页获取属性。现在我运行一个查询

SELECT * FROM table where city like '"+city.text+"'

这里 city.text 从主页选择的城市中获取值。但我的问题是它实际上并没有根据 city.text 中的值显示记录。它显示任何随机记录。

我的代码

主页

<asp:DropDownList ID="locationSelector" runat="server" AutoPostBack="true">
                        <asp:ListItem Selected>Pune</asp:ListItem>
                        <asp:ListItem>Delhi</asp:ListItem>
                        <asp:ListItem>Chennai</asp:ListItem>
                        <asp:ListItem>Bangalore</asp:ListItem>
                        <asp:ListItem>Mumbai</asp:ListItem>
                    </asp:DropDownList>

子页面VB代码

Dim location As DropDownList = Page.Master.FindControl("locationSelector")
        city.Text = location.SelectedItem.ToString

        If Not IsPostBack Then
            Try
                query = "SELECT * FROM hospitals where city like '" + city.Text + "'"
                Dim cmd As New MySqlCommand(query, con)
                cmd.CommandTimeout = 120
                Dim da As New MySqlDataAdapter(cmd)
                Dim table As New DataTable
                da.Fill(table)
                ViewState("Data") = table
                hospitals.DataSource = table
                hospitals.DataBind()

            Catch ex As Exception
                Response.Write(ex)
            End Try
        End If

更新

Protected Sub hospitals_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
        Dim location As DropDownList = Page.Master.FindControl("locationSelector")
        city.Text = location.SelectedItem.ToString
    End Sub

有时它也会抛出超时错误。但大多数时候它会得到结果,但不是根据选定的项目。还有什么其他解决方案?

一些提示:

1) 发生超时错误的原因有很多,包括站点的大量其他流量、连接池全部用完等。对于一小部分城市,我可能会在之后将其保存在缓存中第一次调用,这样你就不需要每次都从数据库中加载城市列表。根据您所在的国家/地区,如果您只有几千个城市,则只需将其放入内存列表中即可。

2) 您使用的 "SELECT *" 通常对其他开发人员来说不是很酷,如果 table 包含的不仅仅是城市名称,对您的代码也不是很酷。如果你写 Select CityName from Table,那么你将有效地减少从数据库到程序的数据量,并且很明显其他开发人员正是您从中得到的东西 table。

3) 如果您有城市的 ID,它的性能可能会更好,因为与匹配几个 ID 相比,字符串匹配真的很慢。我已经看到通过用常量替换字符串提高了 20% 的速度,你不会相信现在代码中的字符串有多慢。

4) 最后,我想您可能已经这样做了,请确保对每个进行 WHERE 筛选的字段进行索引。如果您搜索医院,请确保 Hospitals.City 字段已编入索引以避免行查找。

我希望这(任何)对您有所帮助:)

根据我的理解,您需要进行以下更改

要获取选定的 TEXT 值,请使用 location.SelectedItem.Text 而不是 location.SelectedItem.ToString()

     city.Text = location.SelectedItem.Text // change here

在绑定下拉控件之前检查编号。行数

if(table.Rows.Count>0)
            {
                hospitals.DataSource = table;
                hospitals.DataBind();
            }

我建议在页面内使用预渲染事件。在预呈现事件中尝试访问您的母版页控件并获取值。