JavaScript: Alert.Show(message) From ASP.NET Code-behind

JavaScript: Alert.Show(message) From ASP.NET Code-behind

本文关键字:From ASP NET Code-behind message Alert Show JavaScript      更新时间:2023-09-26

我正在阅读这个JavaScript:Alert.Show(message( From ASP.NET Code-Behind

我正在尝试实现相同的方法。所以我创建了一个这样的静态类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Text;
using System.Web.UI;
namespace Registration.DataAccess
{
    public static class Repository
    {
        /// <summary> 
        /// Shows a client-side JavaScript alert in the browser. 
        /// </summary> 
        /// <param name="message">The message to appear in the alert.</param> 
        public static void Show(string message) 
            { 
               // Cleans the message to allow single quotation marks 
               string cleanMessage = message.Replace("'", "''"); 
               string script = "<script type="text/javascript">alert('" + cleanMessage + "');</script>"; 
               // Gets the executing web page 
               Page page = HttpContext.Current.CurrentHandler as Page; 
               // Checks if the handler is a Page and that the script isn't allready on the Page 
               if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert")) 
               { 
                 page.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script); 
               } 
            } 
    }
}

在这一行上:

string script = "<script type="text/javascript">alert('" + cleanMessage + "');</script>"; 

它向我显示错误:;预期

而且在

page.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script); 

错误:找不到类型或命名空间名称"警报"(您是否缺少 using 指令或程序集引用?

我在这里做错了什么?

这是一个简单的方法:

Response.Write("<script>alert('Hello');</script>");
string script = string.Format("alert('{0}');", cleanMessage);
if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert")) 
{
    page.ClientScript.RegisterClientScriptBlock(page.GetType(), "alert", script, true /* addScriptTags */);
}

此消息直接显示警报消息

ScriptManager.RegisterStartupScript(this,GetType(),"showalert","alert('Only alert Message');",true);

此消息显示来自 JavaScript 函数的警报消息

ScriptManager.RegisterStartupScript(this, GetType(), "displayalertmessage", "Showalert();", true);

这是在 c# 代码隐藏中显示警报消息的两种方法

如果你在页面上使用ScriptManager,那么你也可以尝试使用这个:

System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('Your Message');", true);

试试这个方法:

public static void Show(string message) 
{                
    string cleanMessage = message.Replace("'", "''");                               
    Page page = HttpContext.Current.CurrentHandler as Page; 
    string script = string.Format("alert('{0}');", cleanMessage);
    if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert")) 
    {
        page.ClientScript.RegisterClientScriptBlock(page.GetType(), "alert", script, true /* addScriptTags */);
    } 
} 

在 Vb.Net

Public Sub Show(message As String)
    Dim cleanMessage As String = message.Replace("'", "''")
    Dim page As Page = HttpContext.Current.CurrentHandler
    Dim script As String = String.Format("alert('{0}');", cleanMessage)
    If (page IsNot Nothing And Not page.ClientScript.IsClientScriptBlockRegistered("alert")) Then
        page.ClientScript.RegisterClientScriptBlock(page.GetType(), "alert", script, True) ' /* addScriptTags */
    End If
End Sub

您的代码无法编译。您拥有的字符串意外终止;

string script = "<script type=";

这实际上是你写的。您需要转义双引号:

string script = "<script type='"text/javascript'">alert('" + cleanMessage + "');</script>";

这种事情应该是显而易见的,因为你的源代码着色应该完全被劫持。

不工作的原因可能不止一个。

1:你是否正确调用了你的函数?即

Repository.Show("Your alert message");

2:尝试使用 RegisterStartUpScript 方法而不是脚本块。

3:如果您使用的是UpdatePanel,那也可能是一个问题。

检查这个(主题 3.2(

ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('ID Exists ')</script>");
我认为

,这一行:

string cleanMessage = message.Replace("'", "''"); 

不起作用,它必须是:

string cleanMessage = message.Replace("'", "''''");

您需要用'遮盖',用另一'遮盖'

从代码隐藏调用 JavaScript 函数

步骤 1 添加您的 Javascript 代码

<script type="text/javascript" language="javascript">
    function Func() {
        alert("hello!")
    }
</script>

步骤 2 在您的 webForm 中添加 1 个脚本管理器并添加 1 个按钮

步骤 3 在按钮点击事件中添加此代码

ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "Func()", true);
如果要

显示警告框以显示在同一页上,而不显示在空白页上,请尝试此操作。

ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Sorry there are no attachments');", true);

type="text/javascript" 周围的引号在你想要之前结束你的字符串。在内部使用单引号以避免此问题。

使用这个

type='text/javascript'

您需要修复此行:

string script = "<script type='"text/javascript'">alert('" + cleanMessage + "');</script>"; 

还有这个:

RegisterClientScriptBlock("alert", script); //lose the typeof thing
string script = string.Format("alert('{0}');", cleanMessage);     
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "key_name", script );", true);

100% 工作没有任何问题,不会重定向到另一个页面......我尝试只是复制这个并更改您的消息

// Initialize a string and write Your message it will work
string message = "Helloq World";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("alert('");
sb.Append(message);
sb.Append("');");
ClientScript.RegisterOnSubmitStatement(this.GetType(), "alert", sb.ToString());

尝试:

string script = "<script type='"text/javascript'">alert('" + cleanMessage + "');</script>";

在将客户端代码作为字符串参数发送后,可以使用此方法。

注意:我没有想出这个解决方案,但是当我自己寻找一种方法时,我遇到了它,我只对其进行了一点编辑。

它非常简单且有用,可以使用它来执行超过1行javascript/jquery/...等或任何客户端代码

private void MessageBox(string msg)
{
    Label lbl = new Label();
    lbl.Text = "<script language='javascript'>" + msg + "')</script>";
    Page.Controls.Add(lbl);
}

来源: https://stackoverflow.com/a/9365713/824068

string script = "<script type="text/javascript">alert('" + cleanMessage + "');</script>"; 

你应该使用字符串。在这种情况下为格式。这是更好的编码风格。对你来说,这将是:

string script = string.Format(@"<script type='text/javascript'>alert('{0}');</script>");

另请注意,何时应转义"符号或使用撇号代替。

private void MessageBox(string msg)
{
    Label lbl = new Label();
    lbl.Text  = string.Format(@"<script type='text/javascript'>alert('{0}');</script>",msg);
    Page.Controls.Add(lbl);
}

您需要转义引号(请查看"特殊字符"部分(。您可以通过在它们之前添加斜杠来做到这一点:

string script = "<script type='"text/javascript'">alert('" + cleanMessage + "');</script>";
  Response.Write(script);

我使用它并且可以工作,只要之后页面不重定向。最好让它显示出来,然后等到用户单击"确定",无论重定向如何。

/// <summary>
/// A JavaScript alert class
/// </summary>
public static class webMessageBox
{
/// <summary>
/// Shows a client-side JavaScript alert in the browser.
/// </summary>
/// <param name="message">The message to appear in the alert.</param>
    public static void Show(string message)
    {
       // Cleans the message to allow single quotation marks
       string cleanMessage = message.Replace("'", "'''");
       string wsScript = "<script type='"text/javascript'">alert('" + cleanMessage + "');</script>";
       // Gets the executing web page
       Page page = HttpContext.Current.CurrentHandler as Page;
       // Checks if the handler is a Page and that the script isn't allready on the Page
       if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
       {
           //ClientScript.RegisterStartupScript(this.GetType(), "MessageBox", wsScript, true);
           page.ClientScript.RegisterClientScriptBlock(typeof(webMessageBox), "alert", wsScript, false);
       }
    }    
}

如果事件是特殊的PAGE LOAD事件,则仅调用脚本无法执行此操作。

你需要打电话,Response.Write(script(;

所以如上,字符串脚本 = "alert('" + cleanMessage + "'(;"; Response.Write(script(;

至少可以肯定地用于页面加载事件。

如果你想按摩你的代码隐藏文件,那么试试这个

string popupScript = "<script language=JavaScript>";
popupScript += "alert('Your Massage');";
popupScript += "</";
popupScript += "script>";
Page.RegisterStartupScript("PopupScript", popupScript);

您可以使用以下代码。

 StringBuilder strScript = new StringBuilder();
 strScript.Append("alert('your Message goes here');");
 Page.ClientScript.RegisterStartupScript(this.GetType(),"Script", strScript.ToString(), true);
 <!--Java Script to hide alert message after few second -->
    <script type="text/javascript">
        function HideLabel() {
            var seconds = 5;
            setTimeout(function () {
                document.getElementById("<%=divStatusMsg.ClientID %>").style.display = "none";
            }, seconds * 1000);
        };
    </script>
    <!--Java Script to hide alert message after few second -->

调用消息框很简单,所以如果你想在后面编码或调用函数,我认为它更好,也可能不是。有一个进程,你可以只使用命名空间

using system.widows.forms;
然后,在

要显示消息框的位置,只需将其称为简单,就像在 C# 中一样,如下所示:

messagebox.show("Welcome");