简体   繁体   中英

How to prevent postback from asp.net linkbutton

ASP:

<asp:LinkButton ID="lbSave" OnClick="lbSave_Click" runat="server">Save</asp:LinkButton>

HTML:

<a id="ContentMain_lbSave" href="javascript:__doPostBack(&#39;ctl00$ContentMain$lbSave&#39;,&#39;&#39;)">Save</a>

Code-behind:

public void lbSave_Click(object sender, EventArgs e)
    {
        if (strP != "")
        {
            ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "DiffUser", "showDiffUser();", true);
        }
        else
        {
            //do something else...
        }
    }

JQuery:

function showDiffUser() {
    $("#dvHide").fadeIn("slow");
    $("#backOverlay").fadeIn("slow");
}

When I click the button, I want the page to not do a postback and run the JQuery function. Instead, when I click the link it refreshes the page and then executes the JQuery function.

How can I prevent the postback.

I tried the following: onClientClick='javascript:void(0);' but that doesn't execute the JQuery function.

try

OnClientClick="return false;"

UPDATE:

OnClientClick="showDiffUser();return false;"

showDiffUser(); calls the JS-Method

return false; prevents postback

You only add your jQuery function call to the page after button is clicked. Of course if you suppress the click postback the function call never gets to the page and never gets executed.

What you want though to is to call this function and then suppress, right? Therefore do this:

OnClientClick="showDiffUser(); return false;"

And you do not need the server-side click handler anymore.

If you don't want to cause a postback don't use a .Net LinkButton, use a standard HTML hyperlink instead and use jQuery to capture the event:

<a id="my-link">Save</a>

<script>
$(function () {
   $("#my-link").click(function () {
      showDiffUser();
   });
})
</script>

In the same call, you could do an AJAX call to raise your server-side validation:

<script>
$(function () {
   $("#my-link").click(function () {
      // AJAX Call
        $.ajax({
            type: "post",
            url: "your-url",
            success: function (returnData) {
                showDiffUser();
            }
        });
   });
})
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM