2010-03-11 17 views
6

我在C#中使用asp.net 3.5。當用戶在txtProductID中輸入ProductID時,我需要執行數據庫查找。我想做javascript是不可能的,因爲這必須是服務器端調用。對Textbox onblur事件做一個數據庫查詢

 protected void Page_Load(object sender, EventArgs e) 
    { 
     txtProductID.Attributes.Add("onblur", "LookupProduct()"); 
    } 

     protected void LookupProduct() 
    { 
     //Lookup Product information on onBlur event; 
    } 

我得到一個錯誤信息:微軟JScript運行時錯誤: 我在網頁的Page_Load事件寫了這個代碼預期的對象 我怎樣才能解決這個問題?

回答

3

使用TextBox.TextChanged事件。

ASPX標記:

<asp:TextBox ID="txtProductID" runat="server" AutoPostBack="true" OnTextChanged="txtProductID_TextChanged" /> 

代碼隱藏:

protected void txtProductID_TextChanged(object sender, EventArgs e) 
{ 
    // do your database query here 
} 
+0

請注意,這個答案會導致PostBack,而@ durilai不會。 – jrummell 2010-03-11 18:57:59

1

這應該做的伎倆,作爲參考這裏:http://www.codedigest.com/CodeDigest/80-Calling-a-Serverside-Method-from-JavaScript-in-ASP-Net-AJAX---PageMethods.aspx

這些都是控制

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True" /> 
<asp:TextBox ID="txtTest" onblur="LookupProduct()" runat="server" /> 

這是JavaScript

<script language="javascript"> 
function LookupProduct() 
{ 
    PageMethods.LookupProduct('',OnSuccess, OnFailure); 
} 

function OnSuccess(result) { 
    if (result) 
    { 
    } 
} 

function OnFailure(error) { 
} 
</script> 

這是在服務器sidewebmethod

[WebMethod] 
public static bool LookupProduct() 
{ 
    return true; 
} 
+0

^^雖然已經使用UpdatePanel,這是一種更好的方法來實現這種行爲,onTextChanged事件處理程序或您建議的PageMethods方式? – Dienekes 2010-10-18 09:20:19

+0

這取決於。你想要回傳嗎?如果是這樣的話,那麼'ontextchanged'可能就是要走的路。我圍繞他的標記寫了我的答案,而@ jrummel的答案有更少的代碼。 – 2010-10-18 14:06:55

5

onblur是一個客戶端事件。 LookupProduct是一種服務器端方法。你不能引用另一個 - 兩者之間根本沒有任何關聯。

有沒有快速解決這個問題 - 您必須觸發客戶端事件回發(使用ClientScriptManager.GetPostBackEventReference)或使用像ASP.NET Ajax這樣的庫實現Ajax回調。

另外,如果你並不真的需要對每一個模糊火這種情況下,只有當文本有改變,那麼你可以簡單地使用服務器端TextBox.OnChanged事件和文本框的AutoPostBack屬性設置爲true 。確保你記得設置AutoPostBack,否則這不會讓你任何地方。

+0

需要在TextBox的LostFocus/onBlur上觸發該事件 – user279521 2010-03-11 19:01:57

+0

@ user279521:ASP.NET中沒有服務器端的LostFocus事件,因此如果您必須將它連接到「onblur」事件,那麼您需要如第二段所示構建回發/回調。 – Aaronaught 2010-03-11 19:07:39

+0

@ user279521。看看下面的答案,它將允許你從任何類型的JavaScript事件中調用服務器端方法。 – 2010-03-11 19:20:17