Button Tips And Tricks: Part II

Introduction


In this article we are going to learn how to access the CommandArguments of the button, how to fire JavaScript function on click on the Button and prevent the Form submission, how to avoid multiple clicks while submitting the form on the server, how to post a page to another page in ASP.NET, how to specify the Tab index for the TextBox, Button or any other ASP.Net form control, how to specify the Tooltip for the ASP.NET Server controls and how to specify a default button on the page so that when user hits the Enter key that button gets clicked.

Let's learn all the above mentioned tips and tricks one by one. 

How to access the CommandArguments of the button?

In case we want to set an optional parameter for the button to determine some values in the server side code, we can use this approach.

CommandArguments is a way to get or set optional parameters to the command events along with CommandName.

ASPX PAGE

  <p>

        <asp:Button ID="Button4" runat="server" Text="Sort in Ascending Order"

            CommandName="Sort"

            CommandArgument="Ascending" OnCommand="SortData" /></p>

    <p>

        <asp:Button ID="Button5" runat="server" Text="Sort in Descending Order"

            CommandName="Sort"

            CommandArgument="Descending" OnCommand="SortData" /></

CODE BEHIND 

 protected void SortData(object sender, CommandEventArgs e)

     {

         string commandName = e.CommandName;

         if (commandName.Equals("Sort"))

         {

             var commandArguments = e.CommandArgument;

             if (commandArguments.Equals("Ascending"))

             {

                 Response.Write("Sort in ascending order");

             }

             else if (commandArguments.Equals("Descending"))

             {

                 Response.Write("Sort in descending order");

             }

         }

     }

In the above code snippet, I have specified the same CommandName, OnCommand method for both buttons but different CommandArguments. On click of the first button, "Sort in ascending order" is written and on click on second button "Sort in descending order" is written on the page.

How to fire JavaScript function on click on the Button and prevent the Form submission?

In case we want to fire a JavaScript function on click of the button and prevent web form submission, we can use this approach. 

ASPX PAGE

 <p>

        <asp:Button ID="btnSubmit" runat="server" UseSubmitBehavior="false" OnClientClick="return AlertMe()"

            Text=" Show Alert and Do not submit the form" /></p>

    <script language="javascript" type="text/javascript">

        function AlertMe() {

            alert("JavaScript function called");

            return false;

        }

    </script> 

To fire a JavaScript function in the click event of the asp:Button, we can specify the OnClientClick event of the button to the JavaScript function. 

In the above code, I have placed a button with UseSubmitBehavior=false. In most browsers even if we keep UseSubmitBehavior=false, the form is submitted to the server and we will notice a browser refresh. To avoid this, we can place a return statement on the OnClientClick event and in the JavaScript function we can return false. Returning false stops the form being submitted to the server.

How to avoid multiple clicks while submitting the form on the server?

In case we want to avoid multiple clicks while submitting the form on the server we can use this approach. Generally this is used in case of Payment button or financial application to avoid multiple debit or credit however it can also be used in normal applications to avoid duplicate data submission.

 ASPX PAGE

  <form id="form1" runat="server">

    <div>

        <p>Payment amount: <asp:TextBox ID="txtAmount" runat="server" />

        <asp:RequiredFieldValidator ID="req1" runat="server" Text="*"

        ErrorMessage="Mandatory !" ControlToValidate="txtAmount" />

       </p>

       <p>Description: <asp:TextBox ID="txtDescription" runat="server" /> </p>

       <p><asp:Button ID="btnPay" runat="server" Text="Submit" OnClick="SubmitData"/></p>

    </div>

</form>

CODE BEHIND 

  protected void Page_Load(object sender, EventArgs e)

    {

        // Just disable the button after click

        this.btnPay.Attributes.Add("onclick",

       DisableTheButton(this.Page, this.btnPay));

    }

    protected void SubmitData(object sender, EventArgs e)

    {

        System.Threading.Thread.Sleep(5000);

        Response.Write("Amount: " + txtAmount.Text + " | Description: " + txtDescription.Text);

    }

    // ideally you should keep this into any utility class and call it from the page_load event

    public static string DisableTheButton(Control pge, Control btn)

    {

        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        sb.Append("if (typeof(Page_ClientValidate) == 'function') {");

        sb.Append("if (Page_ClientValidate() == false) { return false; }} ");

        sb.Append("this.value = 'Please wait...';");

        sb.Append("this.disabled = true;");

        sb.Append(pge.Page.GetPostBackEventReference(btn));

        sb.Append(";");

        return sb.ToString();

    }

In the above code snippet (aspx), I have two textboxes (Amount and Description). The Amount is mandatory as I have used RequiredFieldValidator with it. I want to avoid the scenario where a user clicks the Pay button multiple times and the amount will be deducted multiple times (in a real scenario).


OUTPUT 
 

26.JPG

To avoid multiple clicks, we can attach a JavaScript onclick event from the code behind and in that event we can specify DisableTheButton server side method that basically writes the JavaScript code that ensures that the Submit event only fires when ASP.NET Validation have successfully passed and the page is ready to be submitted.


If the ASP.Net client side validation is passed, the button text is changed to "Please wait …" and it is disabled to make sure that end user shall not be able to click on this button again and then the normal do Postback events to fires. These normal do Postback events are written because of the GetPostBackEventReference method called in the last but one line in DisableTheButton server side method.


How to post a page to another page in ASP.NET?


In case we want to post a page to another page in ASP.NET we can use this approach.
 

ASPX PAGE

<p><asp:TextBox ID="txtName" runat="server" /></p>

<p><asp:Button ID="Button1" runat="server" Text="Submit to another page" PostBackUrl="~/PosttoAnotherPageResult.aspx" /></p>

<p><asp:LinkButton ID="lnkSubmit" runat="server" Text="Submit to another page" PostBackUrl="~/PosttoAnotherPageResult.aspx" /></p>


 
To post a page to another page, we can set the PostBackUrl properties of the asp:Button or asp:LinkButton control.

OUTPUT

Source Page

27.JPG
 

On the target page, we need to retrieve the previous page Form data using Request.Form object.

CODE BEHIND - TARGET PAGE (POSTTOANOTHERPAGERESULT.ASPX)

 protected void Page_Load(object sender, EventArgs e)

{

    if (Request.Form != null)

    {

        Response.Write(Request.Form["txtName"]);

    }

}
Target Page 
27b.JPG

How to specify the Tab index for the TextBox, Button or any other ASP.Net form control?

In case we want to specify the tab index to the control so that when the user presses the tab he is navigated to different controls (textbox, dropdown) on the page in a sequence, we can use this approach.

ASPX PAGE

<p><asp:TextBox ID="txtName" runat="server" TabIndex="1" /></p>

<p><asp:TextBox ID="TextBox1" runat="server" TabIndex="3" /></p>

<p><asp:TextBox ID="TextBox2" runat="server" TabIndex="2" /></p>

In the above code, the TabIndex property has been specified to TextBoxes 1, 3 and 2 respectively so if tab key will be pressed from first TextBox the cursor shall jump to third TextBox and then on second TextBox.


This applies to the HTML Form controls as well. 
 

How to specify the Tooltip for the ASP.NET Server controls?

In case we want to specify tooltip for a ASP.Net server controls to give hint to the user about a                             

particular textbox or dropdown etc, we can use this approach. Tooltip appears when user mouse

over that control.

ASPX PAGE

<p><asp:TextBox ID="txtName" runat="server" TabIndex="1" ToolTip="Please enter search keyword" /></p>

<p><asp:TextBox ID="TextBox1" runat="server" TabIndex="3" /></p> 

OUTPUT
 

29.JPG 

To apply the Tooltip for the button or any other ASP.Net server controls, the Tooltip property can be set. As displayed in the above code snippet, I have set "Please enter search keyword" as Tooltip for the first textbox and that is displayed as tooltip to the end user when he/she mouses over it.

How to specify a default button on the page so that when user hits the Enter key that button gets clicked?

In case we have multiple buttons on the data entry page and we want to specify a default button so that when the user hits the enter key after entering data then the default button gets clicked automatically, we can use this approach. 

ASPX PAGE

<form id="form1" runat="server" defaultbutton="Button5">

   <div>

     <p><asp:TextBox ID="txtName" runat="server" TabIndex="1" ToolTip="Please enter search keyword" /></p>

    <p><asp:TextBox ID="TextBox1" runat="server" TabIndex="2" /></p>

    <p><asp:Button ID="Button1" runat="server" Text="Button 1" OnClick="SubmitData" CommandName="Command1" />

    <asp:Button ID="Button2" runat="server" Text="Button 2" OnClick="SubmitData" CommandName="Command2" />

    <asp:Button ID="Button3" runat="server" Text="Button 3" OnClick="SubmitData" CommandName="Command3" />

    <asp:Button ID="Button4" runat="server" Text="Button 4" OnClick="SubmitData" CommandName="Command4" />

    <asp:Button ID="Button5" runat="server" Text="Submit" OnClick="SubmitData"  CommandName="Command5" /></p>

  </div>

</form>

CODE BEHIND

protected void SubmitData(object sender, EventArgs e)

{

    Button btn = (Button)sender;

    Response.Write(btn.CommandName);

}

To specify the default button, we can specify the defaultbutton attribute of the Form element. In the above code snippet, we have 5 buttons and we have specified a defaultbutton to "Button5" so the 5th button shall be active and when use hits enter key after entering the data into the form the 5th button fires. As we have attached SubmitData method to all 5 buttons (you can attach different methods as well) so the same method fires on click of every button and write its CommandName on the page.

OUTPUT
 

30.JPG

Thanks for reading ! Do let us know your feedback.


Similar Articles