Do a database query on Textbox onblur event

坚强是说给别人听的谎言 提交于 2019-12-04 05:17:36

Use the TextBox.TextChanged event.

ASPX markup:

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

Codebehind:

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

onblur is a client-side event. LookupProduct is a server-side method. You can't reference one from the other - there's simply no association whatsoever between the two.

There's no quick fix for this - you have to either trigger a postback on the client event (using ClientScriptManager.GetPostBackEventReference) or implement an Ajax callback using a library like Microsoft ASP.NET Ajax.

Alternatively, if you don't really need to fire this event on every blur, and only when the text has changed, then you can simply use the server-side TextBox.OnChanged event and set the TextBox's AutoPostBack property to true. Make sure you remember to set AutoPostBack, otherwise this won't get you anywhere.

This should do the trick, as referenced here: http://www.codedigest.com/CodeDigest/80-Calling-a-Serverside-Method-from-JavaScript-in-ASP-Net-AJAX---PageMethods.aspx

These are the controls

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

This is the Javascript

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

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

function OnFailure(error) {
}
</script>

This is the server sidewebmethod

[WebMethod]
public static bool LookupProduct()
{
    return true;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!