JavaScript:Alert.Show(消息)如何从ASP.NET代码隐藏?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (17)

我正在阅读这个JavaScript:Alert.Show(message)从ASP.NET代码隐藏

我正在尝试执行相同的操作。所以我创建了一个这样的静态类:

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

Err:无法找到类型或名称空间名称'Alert'(是否缺少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 */);
}

扫码关注云+社区