[英]Javascript alert in C# not working
我只有几个文本框可以查看和更新记录。 这是我的代码,用于在保存或更新之前检查是否有重复记录,并在有任何记录时提醒用户。 javascript警报针对“更新”弹出,而不针对“保存”弹出。 调试器甚至读取else块中的行。 我要去哪里错了?
protected void Save_Click(object sender, EventArgs e)
{
int returnId;
returnId = chkDuplicates(value,1);//function to check for any duplicate value
if(returnId==0)
//save the record
else
ScriptManager.RegisterStartupScript(this,typeof(Page), "MsgSave",
"alert('value exists');", true);
}
protected void Update_Click(object sender, EventArgs e)
{
int returnId;
returnId = chkDuplicates(value,2);//function to check for any duplicate value
if(returnId==0)
//update the record
else
ScriptManager.RegisterStartupScript(this,typeof(Page), "MsgUpdate",
"alert('value exists');", true);
}
请尝试这个,可能会有所帮助
ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(),
"Msg", "alert('value exists');", true);
您是否确定chkDuplicates函数实际上为Save_Click用例返回了一个非零值?
任何方式都不是实现此类用例的适当方式。 最好的方法是将这些方法创建为Web方法,并使用javascript通过按钮单击事件上的ajax调用来调用它们。 如果重复项存在,则抛出一个自定义异常。 这将导致ajax调用发生故障回调。 在此回叫显示水警报中,您需要显示。
这是您优雅地执行操作的方法,并且不会在服务器端代码中注册脚本。 这还将使您的应用程序免于回发和不必要的页面重新加载。
在两个启动脚本中,您的密钥是
“消息”
如果您在RegisterStartupScript方法中查找“字符串键”参数的定义,则会显示“ 脚本块的唯一标识符 ”。 因此它必须与特定页面中的其他键唯一。
在按钮上,添加onClientClick来调用JavaScript。 如果它通过了您,服务器端代码将被调用。
显示javascript警报弹出窗口的另一种方法可能是这样
Response.Write("<script>alert(\"Your text here\");</script>");
试试这个...对我有用....
ClientScript.RegisterStartupScript(typeof(Page), "alertMessage",
"<script type='text/javascript'>alert('value exist');window.location.replace('yourpage.aspx');</script>");
在这里,我们直接显示警报消息
ScriptManager.RegisterStartupScript(this,GetType(),"showalert","alert('Only alert Message');",true);
在这里,我们显示了来自javascript的警报消息
ScriptManager.RegisterStartupScript(this, GetType(), "displayalertmessage", "Showalert();", true);
这是在C#中显示警报消息的两种方式
请确保您没有使用任何“ 更新面板”下的“保存”按钮。 当您执行异步回发时,会发生此问题。 我在新的网页中测试了您的代码,它工作正常。
ASPX页面上的代码
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Save" runat="server" Text="Save" onclick="Save_Click1" />
<asp:Button ID="Update" runat="server" Text="Update" onclick="Update_Click1" /></div>
</form>
</body>
</html>
代码隐藏文件中的代码
protected void Save_Click1(object sender, EventArgs e)
{
int returnId;
returnId = 1;
if (returnId == 0)
{ }
else
ScriptManager.RegisterStartupScript(this, typeof(Page), "MsgSave",
"alert('save value exists');", true);
}
protected void Update_Click1(object sender, EventArgs e)
{
int returnId;
returnId = 2;
if (returnId == 0)
{ }
else
ScriptManager.RegisterStartupScript(this, typeof(Page), "MsgUpdate",
"alert('update value exists');", true);
}
可能会对您有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.