JavaScript:Alert.Show(message)来自ASP.NET的代码隐藏

我正在阅读以下JavaScript:ASP.NET中的Alert.Show(message)代码隐藏

我试图实现相同。 所以我创建了一个像这样的静态类:

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指令或程序集引用?)

我在这里做错了什么?

RG-3 asked 2020-01-14T14:44:04Z
26个解决方案
109 votes

这是一个简单的方法:

Response.Write("<script>alert('Hello');</script>");
Muhammad Akhtar answered 2020-01-14T14:44:12Z
22 votes
string script = string.Format("alert('{0}');", cleanMessage);
if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert")) 
{
    page.ClientScript.RegisterClientScriptBlock(page.GetType(), "alert", script, true /* addScriptTags */);
}
cem answered 2020-01-14T14:44:27Z
18 votes

此消息直接显示警报消息

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

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

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

这是两种在后面的C#代码中显示警报消息的方法

user2561316 answered 2020-01-14T14:44:56Z
9 votes

如果您在页面上使用的是ScriptManager,那么您也可以尝试使用以下命令:

System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('Your Message');", true);
Andrusho answered 2020-01-14T14:45:16Z
5 votes

试试这个方法:

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
Xtian11 answered 2020-01-14T14:45:40Z
4 votes

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

string script = "<script type=";

实际上,这就是您所写的内容。 您需要转义双引号:

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

这种事情应该很明显,因为您的源代码颜色应该完全固定。

Tejs answered 2020-01-14T14:46:12Z
4 votes

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

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

Repository.Show("Your alert message");

2:尝试使用RegisterStartUpScript方法而不是scriptblock。

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

检查一下(主题3.2)

gbs answered 2020-01-14T14:46:50Z
4 votes
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('ID Exists ')</script>");
Ahmad lahham answered 2020-01-14T14:47:05Z
3 votes

我认为,这行:

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

不起作用,它必须是:

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

您需要使用\屏蔽\,并使用另一\屏蔽'

Kirsten answered 2020-01-14T14:47:34Z
3 votes

从代码后面调用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);
Orlando Herrera answered 2020-01-14T14:48:07Z
3 votes

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

ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Sorry there are no attachments');", true);
jithin john answered 2020-01-14T14:48:27Z
2 votes

您需要修复此行:

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

还有这个:

RegisterClientScriptBlock("alert", script); //lose the typeof thing
Adrian Carneiro answered 2020-01-14T14:48:52Z
2 votes
string script = string.Format("alert('{0}');", cleanMessage);     
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "key_name", script );", true);
Nick Kahn answered 2020-01-14T14:49:08Z
2 votes

可以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());
Attaullah Khan answered 2020-01-14T14:49:28Z
1 votes

您想在type =“ text / javascript”前后加上双引号来结束您的字符串。 在内部使用单引号可以避免此问题。

用这个

 type='text/javascript'
R Kitty answered 2020-01-14T14:49:54Z
1 votes

尝试:

string script = "<script type=\"text/javascript\">alert('" + cleanMessage + "');</script>";
Carlos M answered 2020-01-14T14:50:13Z
1 votes

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

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

它非常简单且实用,可以用它执行多于1行的javascript / jquery / ... etc或任何客户端代码

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]

M009 answered 2020-01-14T14:50:47Z
1 votes
string script = "<script type="text/javascript">alert('" + cleanMessage + "');</script>"; 

在这种情况下,您应该使用string.Format。 这是更好的编码样式。 对您来说,它将是:

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

另请注意,当您应转义“符号或改用撇号时。

Jack Spektor answered 2020-01-14T14:51:11Z
1 votes
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);
}
Silvio Marino answered 2020-01-14T14:51:27Z
1 votes

您需要转义引号(请看“特殊字符”部分)。 您可以在它们前面添加一个斜杠来做到这一点:

string script = "<script type=\"text/javascript\">alert('" + cleanMessage + "');</script>";
  Response.Write(script);
blex answered 2020-01-14T14:51:47Z
1 votes

我使用它并且它可以工作,只要页面之后没有重定向。 最好将其显示出来,并且无论重定向如何,都等到用户单击“确定”。

/// <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);
       }
    }    
}
Fandango68 answered 2020-01-14T14:52:07Z
1 votes

仅当事件是PAGE LOAD事件时,调用脚本才不能这样做。

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

如上所述字符串脚本=“ alert('” + cleanMessage +“');”;   Response.Write(script);

可以肯定至少在页面加载事件中有效。

Edwin b answered 2020-01-14T14:52:40Z
1 votes

如果您想按摩文件后面的代码,请尝试此操作

string popupScript = "<script language=JavaScript>";
popupScript += "alert('Your Massage');";

popupScript += "</";
popupScript += "script>";
Page.RegisterStartupScript("PopupScript", popupScript);
Deepak Kushwaha answered 2020-01-14T14:53:01Z
1 votes

您可以使用以下代码。

 StringBuilder strScript = new StringBuilder();
 strScript.Append("alert('your Message goes here');");
 Page.ClientScript.RegisterStartupScript(this.GetType(),"Script", strScript.ToString(), true);
Tabish Usman answered 2020-01-14T14:53:20Z
0 votes
 <!--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 -->
JIYAUL MUSTAPHA answered 2020-01-14T14:53:36Z
-2 votes

调用消息框很简单,因此,如果您想在后面编写代码或调用函数,我认为这是更好的选择,也可能不是。 有一个过程,你可以只使用命名空间

using system.widows.forms;

然后,在要显示消息框的地方,只需像在C#中一样简单地调用它即可,例如:

messagebox.show("Welcome");
Mustafa Iqbal answered 2020-01-14T14:54:00Z
translate from https://stackoverflow.com:/questions/5825165/javascript-alert-showmessage-from-asp-net-code-behind