Disable the postback on an

2019-01-13 19:39发布

I have an ASP.NET linkbutton control on my form. I would like to use it for javascript on the client side and prevent it from posting back to the server. (I'd like to use the linkbutton control so I can skin it and disable it in some cases, so a straight up tag is not preferred).

How do I prevent it from posting back to the server?

17条回答
仙女界的扛把子
2楼-- · 2019-01-13 20:06

Have you tried to use the OnClientClick?

var myLinkButton = new LinkButton { Text = "Click Here", OnClientClick = "JavaScript: return false;" };

<asp:LinkButton ID="someID" runat="server" Text="clicky" OnClientClick="JavaScript: return false;"></asp:LinkButton>
查看更多
男人必须洒脱
3楼-- · 2019-01-13 20:08

You can do it too

...LinkButton ID="BtnForgotPassword" runat="server" OnClientClick="ChangeText('1');return false"...

And it stop the link button postback

查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-01-13 20:08

In the jquery ready function you can do something like below -

var hrefcode = $('a[id*=linkbutton]').attr('href').split(':');
var onclickcode = "javascript: if`(Condition()) {" + hrefcode[1] + ";}";
$('a[id*=linkbutton]').attr('href', onclickcode);
查看更多
冷血范
5楼-- · 2019-01-13 20:09

Something else you can do, if you want to preserve your scroll position is this:

<asp:LinkButton runat="server" id="someId" href="javascript: void;" Text="Click Me" />
查看更多
甜甜的少女心
6楼-- · 2019-01-13 20:09

You might also want to have the client-side function return false.

<asp:LinkButton runat="server" id="button" Text="Click Me" OnClick="myfunction();return false;" AutoPostBack="false" />

You might also consider:

<span runat="server" id="clickableSpan" onclick="myfunction();" class="clickable">Click Me</span>

I use the clickable class to set things like pointer, color, etc. so that its appearance is similar to an anchor tag, but I don't have to worry about it getting posted back or having to do the href="javascript:void(0);" trick.

查看更多
你好瞎i
7楼-- · 2019-01-13 20:12

ASPX code:

<asp:LinkButton ID="someID" runat="server" Text="clicky"></asp:LinkButton>

Code behind:

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        someID.Attributes.Add("onClick", "return false;");
    }
}

What renders as HTML is:

<a onclick="return false;" id="someID" href="javascript:__doPostBack('someID','')">clicky</a>

In this case, what happens is the onclick functionality becomes your validator. If it is false, the "href" link is not executed; however, if it is true the href will get executed. This eliminates your post back.

查看更多
登录 后发表回答