【问题标题】:JavaScript: Alert.Show(message) From ASP.NET Code-behindJavaScript:来自 ASP.NET 代码隐藏的 Alert.Show(message)
【发布时间】:2011-08-15 01:45:49
【问题描述】:

我正在阅读这个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); 

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

我在这里做错了什么?

【问题讨论】:

    标签: c# javascript asp.net


    【解决方案1】:

    type="text/javascript" 周围的引号会提前结束您的字符串。在里面使用单引号可以避免这个问题。

    使用这个

     type='text/javascript'

    【讨论】:

      【解决方案2】:

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

      string script = "<script type=";
      

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

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

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

      【讨论】:

      • 来吧@Tejs,休息一下 :) 连续第三个问题,您提前几秒钟到达 :)
      • 谢谢!警报错误呢?
      • 这可能是劫持代码的副作用。如果不修复早期的错误,就不可能说。
      • 谢谢 Tejs。但我没有从上面的代码中得到任何警报消息。
      • 浏览器(萤火虫、开发者工具、蜻蜓……)说什么?脚本选项卡上有任何错误消息吗?
      【解决方案3】:

      你需要修复这条线:

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

      还有这个:

      RegisterClientScriptBlock("alert", script); //lose the typeof thing
      

      【讨论】:

      • 谢谢!警报错误呢?
      • 谢谢安德里安。但我没有从上面的代码中得到任何警报消息。
      • 你应该一次修复一件事。修复字符串后是否还会出现此错误?
      • 不!错误消失了。构建是成功的,但它没有向我显示任何类型的警报消息..
      【解决方案4】:

      尝试:

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

      【讨论】:

        【解决方案5】:
        string script = string.Format("alert('{0}');", cleanMessage);
        if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert")) 
        {
            page.ClientScript.RegisterClientScriptBlock(page.GetType(), "alert", script, true /* addScriptTags */);
        }
        

        【讨论】:

          【解决方案6】:

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

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

          Repository.Show("Your alert message");
          

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

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

          查看this(topic 3.2)

          【讨论】:

            【解决方案7】:

            这是一个简单的方法:

            Response.Write("<script>alert('Hello');</script>");
            

            【讨论】:

            • 我不喜欢这种方式。你永远不会知道你的代码将被插入到哪里,因为它被插入到流中。它还可能会破坏 HTML 并导致 Javascript 错误。 RegisterClientScriptBlock 是在客户端运行 Javascript 的正确方法。
            【解决方案8】:
            string script = string.Format("alert('{0}');", cleanMessage);     
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "key_name", script );", true);
            

            【讨论】:

              【解决方案9】:

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

              注意:我没有想出这个解决方案,但我在自己寻找方法时遇到了它,我只是稍微修改了一下。

              它非常简单实用,可以使用它来执行超过 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

              【讨论】:

              • 我认为有些部分丢失了。 ""
              【解决方案10】:
              string script = "<script type="text/javascript">alert('" + cleanMessage + "');</script>"; 
              

              在这种情况下,您应该使用 string.Format。这是更好的编码风格。对你来说是:

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

              另请注意,何时应该转义 " 符号或改用撇号。

              【讨论】:

                【解决方案11】:

                试试这个方法:

                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
                

                【讨论】:

                  【解决方案12】:
                  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);
                  }
                  

                  【讨论】:

                    【解决方案13】:

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

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

                    【讨论】:

                    • 这有效,但前提是页面是静态的且未重定向(请参阅我在其他地方的回答)。例如,如果您在此之后有一个 Response.Redirect() 来重新加载页面,则不会显示该消息。需要强制等待,直到用户按下 OK 或其他按钮。
                    • 是的,我们使用与上面类似的代码 v,大部分情况下它对我们有用,但在某些代码中它不起作用,可能是上面 @Fandango68 描述的原因。跨度>
                    【解决方案14】:

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

                    using system.widows.forms;
                    

                    那么,你想在哪里显示一个消息框,就这么简单,就像在 C# 中一样:

                    messagebox.show("Welcome");
                    

                    【讨论】:

                    • 问题是关于在客户端显示一条消息 - 使用 Javascript
                    • 如果是这样的话:^/
                    【解决方案15】:

                    此消息直接显示警报消息

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

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

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

                    这是在c#代码后面显示警报消息的两种方式

                    【讨论】:

                      【解决方案16】:

                      我认为,这条线:

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

                      不行,一定是:

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

                      您需要用\ 屏蔽\,用另一个\ 屏蔽'

                      【讨论】:

                        【解决方案17】:

                        从后面的代码调用 JavaScript 函数

                        第 1 步添加您的 Javascript 代码

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

                        第 2 步在您的 webForm 中添加 1 个 Script Manager 并添加 1 个 按钮

                        第 3 步在您的按钮点击事件中添加此代码

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

                        【讨论】:

                          【解决方案18】:

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

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

                          【讨论】:

                            【解决方案19】:

                            您需要escape your quotes(查看“特殊字符”部分)。您可以通过在它们之前添加一个斜杠来做到这一点:

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

                            【讨论】:

                              【解决方案20】:

                              我使用它并且它可以工作,只要页面之后不重定向。很高兴让它显示,并等待用户点击确定,无论重定向如何。

                              /// <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);
                                     }
                                  }    
                              }
                              

                              【讨论】:

                                【解决方案21】:

                                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());
                                

                                【讨论】:

                                  【解决方案22】:
                                  ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('ID Exists ')</script>");
                                  

                                  【讨论】:

                                  • 请尽量避免只是将代码作为答案转储,并尝试解释它的作用和原因。对于没有相关编码经验的人来说,您的代码可能并不明显。
                                  【解决方案23】:

                                  如果事件是专门的PAGE LOAD事件,调用脚本不能这样做。

                                  你需要打电话, Response.Write(脚本);

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

                                  肯定会至少在页面加载事件中起作用。

                                  【讨论】:

                                  • 示例代码1:string close = @""; base.Response.Write(close);
                                  • 示例代码2:string close = @""; base.Response.Write(close);
                                  【解决方案24】:

                                  如果你想按摩你的代码隐藏文件然后试试这个

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

                                  【讨论】:

                                    【解决方案25】:

                                    您可以使用以下代码。

                                     StringBuilder strScript = new StringBuilder();
                                     strScript.Append("alert('your Message goes here');");
                                     Page.ClientScript.RegisterStartupScript(this.GetType(),"Script", strScript.ToString(), true);
                                    

                                    【讨论】:

                                      【解决方案26】:
                                       <!--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 -->
                                      

                                      【讨论】:

                                        猜你喜欢
                                        • 1970-01-01
                                        • 1970-01-01
                                        • 1970-01-01
                                        • 1970-01-01
                                        • 1970-01-01
                                        • 1970-01-01
                                        • 1970-01-01
                                        • 1970-01-01
                                        • 2015-05-11
                                        相关资源
                                        最近更新 更多