开发者

Do a database query on Textbox onblur event

I am using asp.net 3.5 with C#. I need to do a database lookup when a user enters ProductID in txtProductID. I guess doing javascript is out of the question since this will have to be server side call. I wrote this code in the page_load event of the webpage:

        protected void Page_Load(object sender, EventArgs e)
    {
      开发者_StackOverflow中文版  txtProductID.Attributes.Add("onblur", "LookupProduct()");
    }

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

I get an error message: Microsoft JScript runtime error: Object expected How can I resolve this ?


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.


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
}


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜