在我的search.aspx上,我使用ListView显示搜索结果:
标记:
<asp:TextBox runat="server" ID="txtSearch" placeholder="search" />
<asp:Button runat="server" ID="btnSubmit" Text="Search" OnClick="btnSubmit_Click" />
<asp:ListView ID="ListView1" runat="server">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" ImageUrl='<%# String.Format("../Images/books/{0}.jpg", Eval("Id").ToString()) %>' NavigateUrl='<%# "../books/bookdetails.aspx?BookId=" + Eval("Id").ToString() %>'></asp:HyperLink>
<asp:Label ID="TitleLabel" runat="server" Text='<%# Eval("Title") %>' />
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Publisher") %>' />
<asp:Label ID="Label2" runat="server" Text='<%# Eval("Author") %>' /></p>
</ItemTemplate>
</asp:ListView>
代码背后:
protected void btnSubmit_Click(object sender, EventArgs e)
{
using (ELibraryEntities entities = new ELibraryEntities())
{
var search = from books in entities.Reviews
where books.Title.Contains(txtSearch.Text.Trim())
select books;
ListView1.DataSource = search;
ListView1.DataBind();
}
}
并且工作正常,搜索结果显示在search.aspx页面中。
现在,我想将搜索文本框<asp:TextBox runat="server" ID="txtSearch" placeholder="search" />
移动到MasterPage,因此当用户搜索时,搜索结果将在新的search.aspx页面上打开。
答案 0 :(得分:0)
使用post-redirect-get:
btnSubmit_Click
中的逻辑移至其页面加载事件,同时考虑通过URL传递的搜索字词,而不是直接从文本框中发布。答案 1 :(得分:0)
微软在MSDN上有一篇关于passing values between ASP .NET的好文章,我建议你阅读。在当前设置中,您正在对页面执行操作,然后根据该操作运行代码,该代码从页面上的元素检索数据并执行其他操作。为了拆分搜索框和搜索结果,您需要确保在两个页面之间传递操作,并且内容(搜索查询)在两个页面之间进行通信。
总结一下,您可以采取一些方法:
我建议读入查询字符串方法。作为总结:
//1) On the source page with the search box, you would redirect the user
// to the search results page and append the search query to the URL:
Response.Redirect("search.aspx?search=" + HttpUtility.UrlEncode(query));
//2) On the search results page, parse the query string values
String searchQuery = Request.QueryString["search"];
//3) Perform your search action in code and display the results.
protected void btnSubmit_Click(object sender, EventArgs e){
//your search code
using (ELibraryEntities entities = new ELibraryEntities())
{
var search = from books in entities.Reviews
where books.Title.Contains(searchQuery)
select books;
ListView1.DataSource = search;
ListView1.DataBind();
}
}
请注意使用Response.Redirect,HttpUtility.UrlEncode和Request.QueryString。