如何从服务器端调用确认对话框
问题描述:
我的页面中有一个按钮,其中的单击事件在条件匹配时执行某些代码,否则会要求确认是否继续。我有一个javascript函数来确认,如下所示。如何从服务器端调用确认对话框
<script type="text/javascript">
function getConfirmation(){
var retVal = confirm("Do you want to continue ?");
if(retVal == true){
return true;
}
else{
return false;
}
}
</script>
<asp:Button runat="server" ID="lnkBtn" onClick="lnkBtn_Click" onClientClick="getConfirmation()"></button>
后面的代码看起来是这样的:
void lnkBtn_Click(Object sender, EventArgs e)
{
if (txtMyText.Text!="")
{
///need confirmation here whether to continue.
}
else
{
//continue with normal code.
}
}
现在的问题是确认()被触发时,单击该按钮时,即使条件不满足。我希望confirm()仅在条件满足时触发。请帮我做这个。
感谢您的期待。
我尝试了两种解决方案,但似乎我在某个地方犯了一个错误。我附上下面的完整代码。请求你帮助我找出我错在哪里以及我如何解决它。
<script type="text/javascript">
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("This will completely delete the project. Are you sure?")) {
confirm_value.value = "Yes";
}
else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
</script>
<asp:Button runat="server" ID="lnkBtn" onClick="lnkBtn_Click" onClientClick="getConfirmation()"></button>
代码背后:
protected void ibExport_Click(object sender, ImageClickEventArgs e)
{
string str=gdView.HeaderRow.Cells[8].Text;
System.Web.UI.WebControls.TextBox txtID = (System.Web.UI.WebControls.TextBox)gdView.Rows[0].Cells[8].FindControl(str);
if (txtID.Text != "")
{
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
MyAlert("Yes clicked");
}
else
{
MyAlert("No clicked");
}
}
else
{
MyAlert("No Text found.");
}
}
当ibExport点击与txtID.Text =””,不显示确认对话框!相反,“不点击”警报直接弹出。
答
您非常接近,请在嵌入式点击处理程序中使用return
语句。
onClientClick="return getConfirmation()"
代替
onClientClick="getConfirmation()"
此外,在getConfirmation
功能if
块是多余的
function getConfirmation() {
return confirm("Do you want to continue ?");
}
答
删除你的Javascript。而是在Backend中使用此功能来进行按钮单击事件。
void lnkBtn_Click(Object sender, EventArgs e)
{
if (txtMyText.Text!="")
{
Response.Write("<script> function getConfirmation()"
+" { var retVal = confirm('Do you want to continue ?');"
+" if(retVal == true)"
+" { return true; } else{ return false;} }"
+" </script>");
}
else
{
//continue with normal code.
}
}
这不是网络的工作原理。 – mason