Block an asp:Button OnClick event in C# from the O

2020-07-18 11:25发布

I have an asp:Button on my webpage, and it calls into a JavaScript function and a code-behind method. The latter makes a call to navigate to another page. In the JavaScript function, I'm checking for a condition. If this condition is not met, I want to abort the navigation so that the OnClick method is not called. Is this possible?

<asp:Button OnClick="Button_Click" ID="Action1" OnClientClick="SaveValues()"
    Text="Action1" CssClass="specialButton" runat="server" />

3条回答
不美不萌又怎样
2楼-- · 2020-07-18 11:28

yes it is possible

function SaveValues()
{
if(//check your codition here)
{
return true;
}
else
{
return false;
}
}

<asp:Button OnClick="Button_Click" ID="Action1" OnClientClick="javascript:return SaveValues();" Text="Action1" CssClass="specialButton" runat="server" />
查看更多
Ridiculous、
3楼-- · 2020-07-18 11:45

To block OnClick from executing, just return false from OnClientClick:

<asp:Button OnClick="Button_Click" ID="Action1" OnClientClick="return SaveValues();"
    Text="Action1" CssClass="specialButton" runat="server" />

Assuming that SaveValues will also return a boolean whether or not the condition was met.

查看更多
不美不萌又怎样
4楼-- · 2020-07-18 11:48

Returning true or false, according to the success of the JavaScript, should prevent or enable the button to submit. So, instead of just tacking it on at the end of OnClientClick, where you'd have to conditionalise it and immediately make your call look much more ugly, let the method indicate its operational status.

查看更多
登录 后发表回答