【问题标题】:Retrieve search string from text box on master page for internal search从母版页上的文本框中检索搜索字符串以进行内部搜索
【发布时间】:2012-12-20 01:34:50
【问题描述】:

目前,我的母版页上有一个文本框和一个按钮,用于输入和提交搜索字符串。搜索在我的网站内部。用户将输入搜索字符串,然后单击搜索按钮。搜索按钮重定向到搜索结果页面。搜索结果页面加载时,当前通过上一页的控件搜索搜索字符串文本框来检索搜索字符串。

这一切正常,除非由于异常从登录页面输入搜索:当前用户不允许访问上一页。

所以我想知道检索搜​​索字符串的更好方法是什么。我不希望将重定向 url 与它混淆。我不反对将其存储在 Session 集合中,但在页面加载事件发生之前无法弄清楚如何将其存储到那里。

以下是相关代码:

从母版页:

<asp:TextBox ID="SearchTextBox" runat="server" />
<asp:ImageButton ID="SearchButton" runat="server" Text="Search" PostBackUrl="~/Search.aspx" ImageUrl="~/Graphics/btn_search.png" ImageAlign="AbsMiddle" />

从搜索结果页面:

private string getSearchTextBoxText(Control ctrl)
{
    if (ctrl.HasControls())
    {
        foreach (Control child in ctrl.Controls)
        {
            string s = getSearchTextBoxText(child);

            if (s != null)
                return s;
        }
    }
    else if (ctrl.ID == "SearchTextBox")
    {
        return ((TextBox)ctrl).Text;
    }

    return null;
}

protected void Page_Load(object sender, EventArgs e)
{
    log.Debug("Entering " + MethodBase.GetCurrentMethod().Name);
    string lastSearchText = Label1.Text;
    string searchText = null;

    try
    {
        searchText = PreviousPage != null ? getSearchTextBoxText(PreviousPage) : getSearchTextBoxText(this);
    }
    catch(Exception ex)
    {
        log.Error("Exception occurred attempting to retrieve the search string", ex);
    }
...

【问题讨论】:

  • 您在母版页上有一个搜索文本框,并且希望它的文本出现在任何子页中?我说的对吗?

标签: c# asp.net


【解决方案1】:

我没有正确回答您的问题,但从标题中我可以假设您想要子页面中母版页文本框中的文本。对?为此,请尝试以下代码:

TextBox SearchTextBox= (TextBox)this.Master.FindControl("SearchTextBox");
string searchText = SearchTextBox.Text;

谢谢

【讨论】:

  • 是的,这正是我想要的;如何访问母版页控件。谢谢!
  • @russ 如果有用,请投票,它将增加我的声誉并激励我帮助解决此类问题给其他人。谢谢。
  • 在处理完这个之后,我认为它并不能完全回答我的问题,尽管它确实有帮助。现在,使用Master,很容易得到TextBox的值。但是,从登录页面启动搜索时无法检索它的问题仍然存在。也就是说,要获取搜索字符串,我需要从上一页访问 TextBox。现在,我知道要使用 PreviousPage.Master.FindControl,但是,在这种情况下,PreviousPage 对象是不可访问的,并且仍然会发生上述异常。
  • @russ 登录页面还包含搜索文本框,这很有趣。 :),stackoverflow 是获取解决方案的站点,而不是项目的整个代码。
  • 说真的,有必要吗?为什么在母版页上有一个搜索框很有趣?我在哪里要求任何人为我的项目编写代码?
【解决方案2】:

我可以通过将以下内容添加到 Account 目录中的 Web.config 文件来更正此问题:

<location path="Login.aspx">
    <system.web>
        <authorization>
            <allow users="*"/>
        </authorization>
    </system.web>
</location>

添加后,就可以访问上一页并且可以检索搜索字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-08
    • 2021-03-26
    相关资源
    最近更新 更多