ASP.Net LinkButton Prevent Postback Not Working - JavaScript

孤者浪人 提交于 2019-12-11 16:26:08

问题


I know how to prevent javscript within the href attribute from firing as evident in this JSFiddle (http://jsfiddle.net/mkarr/KNefK/)

However, when this logic is applied to an ASP.Net LinkButton as such:

<asp:LinkButton ID="btnSubmit" runat="server" Text="Submit" OnClientClick="return formTest.validate(event);" OnClick="btnSubmit_Click"></asp:LinkButton>

which translates to:

<a onclick="return formTest.validate(event);" id="ctl00_m_g_87932399_e546_4e12_8297_982b811d8cea_ctl00_btnSubmit" href="javascript:WebForm_DoPostBackWithOptions('blah blah blah')">Submit</a>

The formTest.validate() method does execute correctly and returns false, but the WebForm_DoPostBackWithOptions is always fired immediately after!

Can anyone see any flaws in my logic that I cannot??

EDIT:

Also, several stack overflow solutions have been accepted for this issue but all of them are doing virtually what I have already done leading me to believe I'm missing something simple!

  • Disable the postback on an <ASP:LinkButton>
  • Prevent LinkButton post back OnClientClick not working. Why?

ANSWER:

Since I cannot answer my own question because I'm not reputable yet (LOL), here's an edit with the answer:

Going off @QBM5's original tip of not using ASP.Net controls, I solve the problem, although I still do not know why the initial problem occurred in the first place (does anyone when it comes to ASP.Net? Turn it off, then back on comes to mind here) :o)

I replaced the LinkButton ASP.Net control with the following:

<input type="submit" value="Submit" id="btnSubmitButton" runat="server" OnServerClick="btnSubmitButton_Click" class="submitBtn" />

I then bound the .submitBtn's click event via jQuery:

$('.submitBtn').on('click', function (e) {
    if (!instance.validate()) {
        e.preventDefault();
    }
});

The trick is to use OnServerClick and runat="server" on the control but getting away from LinkButton was the goal and the postback behavior is completely different.

which translates to this:

<input onclick="if (typeof(Page_ClientValidate) == 'function') Page_ClientValidate(''); "  type="submit" id="ctl00_m_g_87932399_e546_4e12_8297_982b811d8cea_ctl00_btnSubmitButton" value="Submit" class="submitBtn">

Anyone want to take a stab at the root cause? I need to move foward so don't have time. :o)

来源:https://stackoverflow.com/questions/24457341/asp-net-linkbutton-prevent-postback-not-working-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!