[英]asp.net button click client and server side code
I have an asp:button
called "Delete" and what I want to do is have a JavaScript confirm popup with the options "Yes" and "No". 我有一个名为“ Delete”的
asp:button
,我想做的是有一个JavaScript确认弹出窗口,带有选项“是”和“否”。 If "Yes" then delete a record from a SQL DB else if "No" then nothing should happen. 如果为“是”,则从SQL DB中删除一条记录,否则为“否”,则什么也不会发生。
<asp:Button runat="server" ID="btnDelete" Text="Delete"
OnClientClick="if(confirm('Delete?'))alert('You chose yes!');else alert('You chose no!')"
OnClick="btnDelete_Click" />
btnDelete_Click
contains SQL delete logic. btnDelete_Click
包含SQL删除逻辑。
The problem I am having is that the OnClick
method always gets executed. 我遇到的问题是,总是会执行
OnClick
方法。 Whether you pick "Yes" or "No" from the JavaScript popup the record gets deleted regardless. 无论是从JavaScript弹出窗口中选择“是”还是“否”,记录都会被删除。 It seems to always cause a postback.
它似乎总是导致回发。
Can I somehow get the "Yes" or "No" result into my code behind so I can actually do a simple "if" statement for the delete logic? 我可以以某种方式在代码中获取“是”或“否”结果,以便实际上为删除逻辑做一个简单的“ if”语句吗?
Try this, on your javascript do this 试试看,在您的JavaScript上执行此操作
var result = Confirm("Are you sure . . . . ");
if(result)
return true;
else
return false;
what it does is if it's true, it should postback your code, else it'd cancel your click. 它是正确的,它应该回发您的代码,否则将取消您的点击。
应该是:
<asp:Button runat="server" ID="btnDeleteSite" Text="Delete" OnClientClick="return confirm('Format Delete?');" OnClick="btnDeleteSite_Click" />
You should ideally put JS event handlers in the script tag, and call them from your OnClientClick event in the button definition. 理想情况下,您应该将JS事件处理程序放在script标记中,并在按钮定义中的OnClientClick事件中调用它们。 Like so:
像这样:
<script type="text/javascript">
function ConfirmDelete() {
return confirm("Delete?");
}
</script>
And then in your button's OnClientClick event, you do this: 然后在按钮的OnClientClick事件中,执行以下操作:
OnClientClick="return ConfirmDelete()"
This keeps your markup clean and readable, and will also prevent the postback from happening if the user chooses 'No'. 这样可以使您的标记清晰,可读,并且如果用户选择“否”,还可以防止发生回发。
Try with this 试试这个
<asp:Button runat="server" ID="btnDelete" Text="Delete" OnClientClick="if(confirm('Delete?')){return true;}else {return false;} OnClick="btnDelete_Click" />
When you are using OnClientClick event with JS confirm dialog box at that time you need to return true or false. 当您在JS确认对话框中使用OnClientClick事件时,您需要返回true或false。 If it will return True then OnClick(Server side) event will fire otherwise it will not.
如果它将返回True,则将触发OnClick(服务器端)事件,否则将不会触发。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.