2012-05-16 36 views
0

我試圖做一個通用的搜索用戶控件,可以給予一些值,基於這些值搜索結果將顯示。但是,我目前正在嘗試顯示我的值的結果,並且它們始終顯示爲我的默認值。Asp.net將值傳遞給用戶控件,然後顯示它們

我的用戶代碼:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ProductSearch.ascx.cs" Inherits="..." %> 
<asp:Label ID="lblSearchWord" runat="server" /> 
<asp:Label ID="lblSearch" runat="server" /> 

代碼背後:

private string _searchWord = string.Empty; 
private int _search = -1; 
public string SearchWord 
     { 
     get { return _searchWord; } 
     set { _searchWord = value; } 
     } 

     public int Search 
     { 
     get { return _search; } 
     set { _search = value; } 
     } 
protected void Page_Load(object sender, EventArgs e) 
     { 
     lblGroupId.Text = LevelId.ToString(); 
     lblSearchWord.Text = SearchWord; 
} 

當我按下主aspx.cs頁面上的搜索按鈕,我執行以下操作:

protected void btnSearch_Click(object sender, EventArgs e) 
     { 
      ucPS.SearchWord = txtProductSearch.Text; 
      ucPS.Search = 1 
} 

我的aspx頁面包含以下內容

<%@ Register src="UserControls/ProductSearch.ascx" tagname="ProductSearch" tagprefix="ps" %> 
<ps:ProductSearch id="ucPS" runat="server" /> 

我的問題是,我不能使用查詢字符串,因爲用戶可能已經選擇了一些其他的東西,我需要保持這個狀態,但是我沒有測試過那個,然後開始工作。

我哪裏錯了?還是有更好的選擇(查詢字符串除外)。

回答

3

頁面中的所有變量均位於page-lifecycle的末尾。因此SearchWord將始終在每次回發時使用默認值進行初始化。

您需要將其保存在其他地方,例如在ViewState變量中。

public string SearchWord 
{ 
    get 
    { 
     if (ViewState["SearchWord"] == null) 
      return ""; 
     else 
      return (String)ViewState["SearchWord"]; 
    } 
    set { ViewState["SearchWord"] = value; } 
} 

Nine Options for Managing Persistent User State in Your ASP.NET Application

+0

謝謝,我完全忘了ViewState的,這個固定我的問題。 – Lex

3
public string SearchWord 
{ 
    get 
    { 
     if (ViewState["SearchWord"] == null) 
      ViewState["SearchWord"] = string.Empty; 

     return ViewState["SearchWord"]; 
    } 
    set 
    { 
     ViewState["SearchWord"] = value; 
    } 
} 

,我使用數據綁定不是頁面加載,這樣一來,除非你把它叫做你的用戶控件不加載。

protected override DataBind() 
{ 
    //you can add a condition here if you like 
    if(SearchWord != string.Empty) 
     lblSearchWord.Text = SearchWord; 
} 

從ASPX稱之爲:

usercontrol.SearchWord = "my word"; 
usercontrol.DataBind(); 

和多數民衆贊成它..

相關問題