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('ctl00$ContentMain$lbSave','')">Save</a>
Code for:
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 postback and run the JQuery function. Instead, when I click on the link, it refreshes the page and then executes a JQuery function.
How can I prevent postback.
I have tried the following onClientClick='javascript:void(0);'
, but this fails the JQuery function.
try
OnClientClick="return false;"
UPDATE:
OnClientClick="showDiffUser();return false;"
showDiffUser();
calls JS method
return false;
prevents reverse transmission
You only add a jQuery function call to the page after the 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 is to call this function and then suppress, right? So do the following:
OnClientClick="showDiffUser(); return false;"
And you don't need a server side click handler anymore.
If you don't want the postback not to use the .Net LinkButton then use the standard HTML hyperlink 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 can make an AJAX call to raise the server side confirmation:
<script>
$(function () {
$("#my-link").click(function () {
// AJAX Call
$.ajax({
type: "post",
url: "your-url",
success: function (returnData) {
showDiffUser();
}
});
});
})
</script>