Home » Asp.netRSS

asp:textbox TextChanged event


I have a textbox in my app in which I have code behind in the "onTextChanged" event that I'd like to execute  without doing an entire page post back . 

I can't use use AJAX not an option for me (corporate thing). 

Anyways, I have been struggling with the specifics on implementing ICallbackEventHandler. Or is than another way I can/should do this.

The code in the textChanged event pulls a dataset from the DB and does a validation.

Any advice is appreciated.

Thanks

 

 

 

 

21 Answers Found

 

Answer 1

Here is the link to how to implement the ICallbackEventHandler

http://msdn.microsoft.com/en-us/library/ms178208(v=VS.90).aspx.


Another way to do it is calling a web service using Jquery.

on the onchange event, you use javascript to call the web service to do the validation, then on the callback method, you can 

diplay a message or any business logic that you are required.

 

Answer 2

Thanks for the post!

im trying to work through an example using the link you provided  while applying it to my scenario...

I am getting this issue first on build:

 "Error 1 'CallServer' is not a member of 'ASP.srchexp_aspx'. C:\VSprojects\srchExp.aspx 68 "

which refers to the below line on my Mark Up page.

<asp:TextBoxID="srCtr"runat="server"Width="86px"OnTextChanged="CallServer('1', alert('Callback sent to Server'))"></asp:TextBox></td>

Additionally this is my code  behind and javascript, do they look OK?

Code Behind

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        
        Dim cm As ClientScriptManager = Page.ClientScript
        Dim cbReference As String
        cbReference = cm.GetCallbackEventReference(Me.srCtr, "onTextChanged", "ReceiveServerData", "")
        Dim callbackScript As String = ""
        callbackScript &= "function CallServer(arg, context)" & "{" & cbReference & "; }"
        cm.RegisterClientScriptBlock(Me.GetType(), "CallServer", callbackScript, True)

javascript:

     function ReceiveServerData(arg, context) 
     {
       ///not sure what to put here???
     }


 


 

 

Answer 3

You can try this open source framework providing CallBack feature for asp  controls instead of postback.

http://anthem.talloaksoftware.com/Extensions/TextBox.aspx

you can add a reference and use that control like a regular control. Try that and see if it works.

 

Answer 4

Thank you!  This Anthem.net worked great..does exactly what I want it to do... However...i didn't learn anything.  I have implemented this into my app  temporarily until I can figure out how to do this myself.  I don't want to be reliant on someone elses delivered .dll's.

Thanks so much though. 

 

Answer 5

 

Am trying to implement iCallBackEventHandler following the example
in the above msdn link and am getting the following error on build..

Error 1 'CallServer' is not a member of 'ASP.srchexp_aspx'. C:\VSprojects\srchExp.aspx 84 

not really sure why this doesn't work..
seems straight forward to me. 
what am I missing?

Mark Up....

<td style="width: 6462px; height: 26px">
                        <asp:TextBox ID="srCtrOld" runat="server" Width="86px" Visible="true"  OnTextChanged="CallServer('1', alert('Callback sent to Server'));"  >
                        </asp:TextBox>
                    </td>


 

 

Code Behind

Partial Class CallBack_DB_aspx
    Inherits System.Web.UI.Page
    Implements System.Web.UI.ICallbackEventHandler

    Public Sub RaiseCallbackEvent(ByVal eventArgument As String) Implements System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent
        'Processes a callback event  on the server using the event
        'argument from the client.
        Dim instance As ICallbackEventHandler
        instance.RaiseCallbackEvent("OnTextChanged")
    End Sub
    Public Function GetCallbackResult() As String Implements System.Web.UI.ICallbackEventHandler.GetCallbackResult
        Dim result As String
        result = ""
        Return result
    End Function
End Class


Partial Class srchExp
        Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim bldvw As base = New base

        Dim cm As ClientScriptManager = Page.ClientScript
        Dim cbReference As String
        cbReference = cm.GetCallbackEventReference(Me.srCtrOld, "OnChange", "ReceiveServerData", "")
        Dim callbackScript As String = ""
        callbackScript = "function CallServer(arg, context)" & "{" & cbReference & "; }"
        cm.RegisterClientScriptBlock(Me.GetType(), "CallServer", callbackScript, True)

.....


 

 

 


 

 

 

Answer 6

Is jQuery an option?

You could use jquery to call server side webmethod/webservice etc, that does your validation and based on the o/p do your processing. 

 

Answer 7

I don't know....i'd defer back  because I don't know jQuery...what it is or can do.

What I am attempting to do is to get my OnTextChanged event  to fire without doing a full postback.   

 
 

Answer 9

does this require having ajax extensions installed?

I can't do that due to some corporate  red tape 

 

Answer 10

No, you just have to either download the jquery js file or include the jquery file as CDN as I have included in that example 

 

Answer 11

in the example located at that link...the button is not pointing to any event.  I didn't see any code for the button's  On_click event  in the code  behind page  illustrated.

How would this example relate to a textbox  and its OnTextChanged event? 

 

Answer 12

Ok..i tried to mimic your example to my scenario..i receive no build or runtime errors however the code behind method is not being fired.  what am i doing wrong.

Mark Up:

 <td style="width: 6462px; height: 26px">
                        <asp:TextBox  ID="srCtrOld"  runat="server" Width="86px" Visible="true" >
                        </asp:TextBox>
  </td>


jQuery:

<script src="jquery.min.js" type="text/javascript" ></script>
<script type="text/javascript">
$(document).ready(function () 
{             
    $('#<%=srCtrOld.ClientID %>').TextChanged(function () 
    {   
       $.ajax(
       {   
        type: "POST",   
        url: "srchExp.aspx/testUp",   
        data: "{}",  
        contentType: "application/json; charset=utf-8",  
        dataType: "json",  
        async: true,  
        cache: false,  
        success: function (msg) 
        {  
         $('#myDiv').text(msg.d);   
        }         
       })             
       return false;  
    });      
})
</script>


 

Code Behind:

    Protected Sub testUp(ByVal sender As Object, ByVal e As EventArgs)
        MsgBox("inside testup without postback")
    End Sub


 

 

Answer 13

again, my goal is simply to fire off the OnTextChanged event  without a full postback...  nothing else, I do not need a return message

thanks

 

Answer 14

//Javascript:

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
function Validate(txt)
{
  $.ajax(   
       {      
        type: "POST",      
        url: "Default2.aspx/MyServerSideMethod",      
        data: '{ "a": "' + txt.value + '"}',    
        contentType: "application/json; charset=utf-8",     
        dataType: "json",     
        async: true,     
        success: function (msg)    
        {     
         $('#msg').text(msg.d);   
        }            
       });
       return false;              
        
}
</script>
//above code  will be called on change of your texbox and pass the value of the
//texbox to the server side method, which then returns the value typed back
//and updates the div (just an example)

//aspx:

 <asp:TextBox ID="TextBox1" runat="server"  onchange="return Validate(this);"      />
    <div id="msg"></div>   


//Code behind (c#):
 [WebMethod]
    public static string MyServerSideMethod(string a)
    {
        //Your Logic
        return a;
    }

//this is a webmethod in your code behind file
// you could also use a webmethod in your webservice or a method in your webhandler


See the above sample, its a working solution.

 

 

Answer 15

thank you very much for the messages. much appreciated.

if I change my markup to:

 

<asp:TextBoxID="srCtrOld"runat="server"Width="86px"Visible="true"OnTextChanged="return otc();">

 </asp:TextBox>

I get this error:  Error 1 'return' is not a member of 'ASP.srchexp_aspx'. C:\VSprojects\srchExp.aspx 105 

If i keep my mark up just as you have it:

<

asp:TextBoxID="srCtrOld"runat="server"Width="86px"Visible="true"onchange="return otc();">

 </asp:TextBox>

Build is successful, app  runs, but the code  behind method is not called.

jQuery is now:

<script src="jquery.min.js" type="text/javascript" ></script>
<script type="text/javascript">
$(document).ready(function otc() 
{             
    $('#<%=srCtrOld.ClientID %>').TextChanged(function () 
    {   
       $.ajax(
       {   
        type: "POST",   
        url: "srchExp.aspx/testUp",   
        data: "{}",  
        contentType: "application/json; charset=utf-8",  
        dataType: "json",  
        async: true,           
       })              
    });      
})
</script>


again I do not want to pass any value or retrieve any value into a variable...i simply want to fire off an event: OnTextChanged.

 

 

Answer 16

If you read my post  and try to use the same way I did you should not have any problems.

OnTextChanged is a server side event  associated with the textbox, which I am not using.

I am using onchange which is a javascript event of textbox.

In that event I am calling a javascript event called as Validate which makes a ajax  call to the server side WebMethod 

Note: It has to be a webmethod in the code  behind, a web method in webservice or a method in the ashx handler.

In the above method I use a web method in my code behind.

So revising your code above, use this:

<script src="jquery.min.js" type="text/javascript" ></script>
<script type="text/javascript">
function otc()
{
  $.ajax(   
       {      
        type: "POST",      
        url: "srchExp.aspx/testUp",      
        data: "{}",    
        contentType: "application/json; charset=utf-8",     
        dataType: "json",     
        async: true
      });
       return false;           
}
</script>

<asp:TextBox ID="srCtrOld" runat="server" Width="86px" Visible="true"  onchange="return otc();" > 
 </asp:TextBox>


Return false after the statement prevents postback.

Retr

 

Answer 17

oxfield1:
how to do this myself

Check this example

Markup:

<html>
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function GridCallBackSuccess(callbackResult) {
            document.getElementById('dvGridView').innerHTML = callbackResult;
            showProgress(false);
        }
        function showProgress(flag) {
            if (flag) {
                document.getElementById('imgProgress').style.display = 'block';
                document.getElementById('dvGridView').style.display = 'none';
                document.getElementById('txtValue').disabled = true;
            }
            else {
                document.getElementById('imgProgress').style.display = 'none';
                document.getElementById('dvGridView').style.display = 'block';
                document.getElementById('txtValue').disabled = false;
            }
        } 
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <table>
        <tr>
            <td>
                <asp:TextBox ID="txtValue" Width="145px" runat="server" 
                onchange="updateGridView('RefreshGridView');"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td colspan="2" align="center">
                <img src="Images/load.gif" alt="Load" id="imgProgress" style="display: none;" />
            </td>
        </tr>
        <tr>
            <td>
                <div id="dvGridView" style="height: 200px; overflow: auto; width: 150px;">
                    <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" 
                                  GridLines="None">
                        <RowStyle BackColor="#EFF3FB" />
                        <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
                        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                        <EditRowStyle BackColor="#2461BF" />
                        <AlternatingRowStyle BackColor="White" />
                    </asp:GridView>
                </div>
            </td>
        </tr>
    </table>
    </form>
</body>
</html>

Code Behind:

Public Class CallBackDemo
    Inherits System.Web.UI.Page
    Implements ICallbackEventHandler
    Private m_EventArgument As String = ""
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Page.ClientScript.RegisterClientScriptBlock(GetType(Page),
             "GridServerMethod",
             "function updateGridView(parameter) {  showProgress(true);" + _
             Page.ClientScript.GetCallbackEventReference(Me,"parameter","GridCallBackSuccess","")+
             "; }", True)
    End Sub
    Public Sub RaiseCallbackEvent(ByVal eventArgument As String) Implements _
              System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent
        m_EventArgument = eventArgument
        Select Case eventArgument
            Case "RefreshGridView"
                GridView1.DataSource = Enumerable.Range(1, 100) _
                                                .Select(Function(a) _
                                                 New With _
                                                 { _
                                                     .ID = a, _
                                                     .Name = String.Format("Test Name {0}", a) _
                                                 }).ToList()
                GridView1.DataBind()
        End Select
    End Sub
    Public Function GetCallbackResult() As String _
        Implements System.Web.UI.ICallbackEventHandler.GetCallbackResult
        Dim strCallBackResult As String = ""
        Threading.Thread.Sleep(3000)
        Select Case m_EventArgument
            Case "RefreshGridView"
                Using StringWriter1 As New System.IO.StringWriter()
                    GridView1.RenderControl(New HtmlTextWriter(StringWriter1))
                    strCallBackResult = StringWriter1.ToString()
                End Using
        End Select
        Return strCallBackResult
    End Function
End Class

Make sure that you use same function name from Callback event  Reference in your text change event. CallBack result will be a string and you cannot update controls directly. If you see Anthem dll source code(AutoUpdateAfterCallBack property), GridView is being rendered in a div and textbox  is rendered in a span etc, etc, with CallBack Result. And you have to check for StringArgument value and write code  in switch block. You can try this if you prefer using callback.

 

Answer 18

Thank you very much Sansan..that was very helpful...

I have my example working.  I have one issue with it.  In the service side sub that I have being fired...i make the following call that suddenly seems not to fire.  would you know why?

my RaiseCallbackEvent calls another local sub (ctrchange).  In this sub i have:

.....If rdr.HasRows Then
                srActiv.Focus()
            Else
                msg = "alert('This is not a valid center in your profile');"
                If (Not ClientScript.IsStartupScriptRegistered("ctralert")) Then
                    Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "ctralert", msg, True)
                End If
                GridView1.Visible = False
            End If

when I step through during execution, I hit the Page.ClientScript.RegisterClientScriptBlock statement, however the alert never fires.  This is a sudden occurrence

 

Answer 19

is there something i am missing in the above code, regarding the registered script, that is preventing the alert message from firing.   Stepping through the code is being hit, but no alert arises.

thanks

 

Answer 20

If you are using AJAX, use ScriptManager.RegisterStartupScriptBlock.

 

Answer 21

i am not using ajax...also use the same block of code in many other places...its not working here and I wonder if it has something to do with the fact that the CallBackEventHandler is calling this sub?

 
 
 

<< Previous      Next >>


Microsoft   |   Windows   |   Visual Studio   |   Follow us on Twitter