Monday, May 16, 2011

how to forcefully postback from javascript in ASP.Net


I am taking a simple example and telling you the way how to achieve this.
Example:
    I want to postback my page when user presses "Enter" key while focus is in textbox. Write the following code in this way.
Page.aspx.cs
on page load write the following code:
txtbox1.Attributes.Add("onKeyPress", "KeyPressTextBox()");

User can check that value passed from cleint side in his page like this and he/she can ignore any other calls on this argument value

protected void Page_Load(object sender, EventArgs e)
{
if(HttpContext.Current.Request.Params["__EVENTARGUMENT"] == "argument")
        {
            // Enter you code
        }
            return;
}

Page.aspx

 <script type="text/javascript">
  function KeyPressTextBox() {
  //var KeyID = (window.event) ? event.keyCode : e.keyCode;
    if (event.keyCode == 13) {
       event.returnValue = false;
       event.cancelBubble = true;
      __doPostBack('<%=UpdatePanel1.ClientID %>', "argument");
            }
        }
 </script>


 <asp:UpdatePanel ID="UpdatePanel1" runat="server">
          <ContentTemplate>
             <asp:TextBox ID="txtbox1" runat="server" Width="160px"></asp:TextBox>
          </ContentTemplate>
     </asp:UpdatePanel>

No comments:

Post a Comment