[.net] How to disable postback on an asp Button (System.Web.UI.WebControls.Button)

I have an asp button. It's server-side so I can only show it for logged in users, but i want it to run a javascript function and it seems when it's runat="server" it always calls the postback event.

I also have a regular button (<input...>) not running at server and it works fine...

How can I make this button only run the javascript and not postback?

This question is related to .net asp.net javascript ajax

The answer is


You can use jquery click action and use the preventDefault() function to avoid postback

<asp:button ID="btnMyButton" runat="server" Text="MyButton" />


$("#btnMyButton").click(function (e) {
// some actions here
 e.preventDefault();
}

The others are right that you need your callback to return false; however I'd like to add that doing it by setting the onclick is an ugly old way of doing things. I'd recommend reading about unobtrusive javascript. Using a library like jQuery could make your life easier, and the HTML less coupled to your javascript (and jQuery's supported by Microsoft now!)


you can use the code:

_x000D_
_x000D_
<asp:Button ID="Button2" runat="server"_x000D_
     Text="Pulsa"_x000D_
     OnClientClick="this.disabled=true"_x000D_
     UseSubmitBehavior="False"/>
_x000D_
_x000D_
_x000D_

if nee submit

_x000D_
_x000D_
..._x000D_
<form id="form1" runat="server" onsubmit="deshabilita()">_x000D_
..._x000D_
<script type="text/javascript">_x000D_
    function deshabilita()_x000D_
    {_x000D_
        var btn = "<%= Button1.ClientID %>";_x000D_
        if (confirm("Confirme postback"))_x000D_
        {_x000D_
            document.getElementById(btn).disabled = true;_x000D_
            return true;_x000D_
        }_x000D_
        return false;_x000D_
    }_x000D_
</script>
_x000D_
_x000D_
_x000D_


You just need to return false from the

_x000D_
_x000D_
function jsFunction() {
  try {
    // Logic goes here
    return false; // true for postback and false for not postback
  } catch (e) {
    alert(e.message);
    return false;
  }
}
_x000D_
<asp:button runat="server" id="btnSubmit" OnClientClick="return jsFunction()" />
_x000D_
_x000D_
_x000D_

JavaScript function like below.

Note*: Always use try-catch blocks and return false from catch block to prevent incorrect calculation in javaScript function.


ASP.NET always generate asp:Button as an input type=submit.
If you want a button which doesn't do a post, but need some control for the element on the server side, create a simple HTML input with attributes type=button and runat=server.

If you disable click actions doing OnClientClick=return false, it won't do anything on click, unless you create a function like:

function btnClick() {
    // do stuff
    return false;
}

YourButton.Attributes.Add("onclick", "return false");

or

<asp:button runat="server" ... OnClientClick="return false" />

additionally for accepted answer you can use UseSubmitBehavior="false" MSDN


In my case, I solved adding return in the onClientClick:

Code Behind

function verify(){
  if (document.getElementById("idName").checked == "") {
    alert("Fill the field");
    return false;
  }
}

Design Surface

<asp:Button runat="server" ID="send" Text="Send" onClientClick="return verify()" />

You can use JQuery for this

<asp:Button runat="server" ID="btnID" />

than in JQuery

$("#btnID").click(function(e){e.preventDefault();})

With Validation

In this example I used two controls,ddl and txtbox, have a happy coding

 asp:ScriptManager ID="script1" runat="server" /asp:ScriptManager

    asp:UpdatePanel ID="Panel1" runat="server"
       ContentTemplate

// ASP BUTTON
asp:Button ID="btnSave" runat="server" Text="Save" class="btn btn-success" OnClientClick="return Valid()" OnClick="btnSave_Click"


   /ContentTemplate    
    /asp:UpdatePanel    

  <script type="text/javascript">
        function Valid() {

            if ($("#ctl00_ContentPlaceHolder1_YOUR CONTROL NAME").val() == 0) {
                alert("Please select YOUR TEXT");
                $("#ctl00_ContentPlaceHolder1_YOUR CONTROL NAME").focus();
                return false;
            }

            if ($("#ctl00_ContentPlaceHolder1_YOUR CONTROL NAME").val().length == 0) {
                alert("Please Type YOUR TEXT");
                $("ctl00_ContentPlaceHolder1_YOUR CONTROL NAME").focus();
                return false;
            }
            return true;
        }
</script>

You don't say which version of the .NET framework you are using.

If you are using v2.0 or greater you could use the OnClientClick property to execute a Javascript function when the button's onclick event is raised.

All you have to do to prevent a server postback occuring is return false from the called JavaScript function.


Consider this.

<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequest);
function BeginRequest(sender, e) {
    e.get_postBackElement().disabled = true;

}
     </script>

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios