简体   繁体   English

使用C#从母版页获取文本框值

[英]Get Textbox Value from Masterpage using c#

I have a search textbox situated on a masterpage like so: 我的主页上有一个搜索文本框,如下所示:

<asp:TextBox ID="frmSearch" runat="server" CssClass="searchbox"></asp:TextBox>
<asp:LinkButton ID="searchGo" PostBackUrl="search.aspx"  runat="server">GO</asp:LinkButton>

The code behind for the search page has the following to pick up the textbox value (snippet): 搜索页面后面的代码具有以下内容,可用来拾取文本框值(摘要):

if (PreviousPage != null && PreviousPage.IsCrossPagePostBack)
        {
            Page previousPage = PreviousPage;
            TextBox tbSearch = (TextBox)PreviousPage.Master.FindControl("frmSearch");
            searchValue.Text = tbSearch.Text;

            //more code here...
        }

All works great. 一切都很好。 BUT not if you enter a value whilst actually on search.aspx, which obviously isn't a previous page. 但是如果您实际上在search.aspx上输入了一个值,则不会,但显然不是上一页。 How can I get round this dead end I've put myself in? 我该如何克服自己陷入的困境?

If you use the @MasterType in the page directive, then you will have a strongly-typed master page, meaning you can access exposed properties, controls, et cetera, without the need the do lookups: 如果在page指令中使用@MasterType ,那么您将拥有一个强类型的母版页,这意味着您可以访问公开的属性,控件等,而无需执行do查找:

<%@ MasterType VirtualPath="MasterSourceType.master" %>

searchValue.Text = PreviousPage.Master.frmSearch.Text;

EDIT: In order to help stretch your imagination a little, consider an extremely simple property exposed by the master page: 编辑:为了帮助您扩展想象力,请考虑母版页公开的一个非常简单的属性:

public string SearchQuery 
{
    get { return frmSearch.Text; }
    set { frmSearch.Text = value; }
}

Then, through no stroke of ingenuity whatsoever, it can be seen that we can access it like so: 然后,无论如何都不会创造力,可以看出我们可以像这样访问它:

searchValue.Text = PreviousPage.Master.SearchQuery;

Or, 要么,

PreviousPage.Master.SearchQuery = "a query";

All you need is: 所有你需要的是:

TextBox tbSearch = (TextBox)PreviousPage.Master.FindControl("frmSearch");
searchValue.Text = tbSearch.Text;

No need to worry about whatever 'previous page' is. 无需担心“上一页”是什么。

As @Mr.Disappointment also says you should look at having strongly-typed access . 正如@ Mr.Disappointment还说的那样,您应该查看具有强类型的访问权限

Here is a solution (but I guess its old now): 这是一个解决方案(但我想现在已经过时了):

    {
        if (PreviousPage == null)
        {
            TextBox tbSearch = (TextBox)Master.FindControl("txtSearch");
            searchValue.Value = tbSearch.Text;
        }
        else
        {
            TextBox tbSearch = (TextBox)PreviousPage.Master.FindControl("txtSearch");
            searchValue.Value = tbSearch.Text;             
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM