简体   繁体   English

JavaScript:Alert.Show(消息)来自ASP.NET代码隐藏

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

I am reading this JavaScript: Alert.Show(message) From ASP.NET Code-behind 我正在阅读这个JavaScript:Alert.Show(消息)来自ASP.NET代码隐藏

I am trying to implement the same. 我正在努力实现同样的目标。 So I created a static class like this: 所以我创建了一个这样的静态类:

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

On this line: 在这一行:

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

It is showing me the error: ; 它向我显示错误: ; Expected 预期

And also on 还有

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

Err: The type or namespace name 'Alert' could not be found (are you missing a using directive or an assembly reference?) 错误: 找不到类型或命名空间名称“警报”(您是否缺少using指令或程序集引用?)

What am I doing wrong here? 我在这做错了什么?

这是一个简单的方法:

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

This message show the alert message directly 此消息直接显示警报消息

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

This message show alert message from JavaScript function 此消息显示来自JavaScript函数的警报消息

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

These are two ways to display alert messages in c# code behind 这两种方法可以在后面的c#代码中显示警报消息

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

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

Try this method: 试试这个方法:

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

In Vb.Net 在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
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('ID Exists ')</script>");

Your code does not compile. 您的代码无法编译。 The string you have terminates unexpectedly; 你已经意外终止的字符串;

string script = "<script type=";

That's effectively what you've written. 这实际上就是你写的。 You need to escape your double quotes: 你需要逃避双引号:

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

This kind of thing should be painfully obvious since your source code coloring should be completely jacked. 这种事情应该是非常明显的,因为你的源代码着色应该完全被填满。

There could be more than one reasons for not working. 不工作的原因可能不止一个。

1: Are you calling your function properly? 1:你是否正确地调用了你的功能? ie

Repository.Show("Your alert message");

2: Try using RegisterStartUpScript method instead of scriptblock. 2:尝试使用RegisterStartUpScript方法而不是scriptblock。

3: If you are using UpdatePanel, that could be an issue as well. 3:如果您使用的是UpdatePanel,那么这也可能是一个问题。

Check this(topic 3.2) 检查一下(主题3.2)

And i think, the line: 我认为,这条线:

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

does not work, it must be: 不起作用,必须是:

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

You need to mask the \\ with a \\ and the ' with another \\ . 你需要屏蔽\\\\'与其他\\

Calling a JavaScript function from code behind 从后面的代码调用JavaScript函数

Step 1 Add your Javascript code 第1步添加您的Javascript代码

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

Step 2 Add 1 Script Manager in your webForm and Add 1 button too 步骤2在webForm中添加1个脚本管理器 ,并添加1 按钮

Step 3 Add this code in your button click event 步骤3在按钮单击事件中添加此代码

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

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

ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Sorry there are no attachments');", true);
string script = string.Format("alert('{0}');", cleanMessage);     
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "key_name", script );", true);

Works 100% without any problem and will not redirect to another page...I tried just copying this and changing your message 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());

You need to fix this line: 您需要修复此行:

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

And also this one: 还有这一个:

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

You can use this method after sending the client-side code as a string parameter. 将客户端代码作为字符串参数发送后,可以使用此方法。

NOTE : I didn't come up with this solution, but I came across it when I was searching for a way to do so myself, I only edited it a little. 注意 :我没有提出这个解决方案,但是当我自己寻找一种方法时,我遇到了它,我只编辑了一点。

It is very simple and helpful, and can use it to perform more than 1 line of javascript/jquery/...etc or any client-side code 它非常简单和有用,可以用它来执行超过1行的javascript / jquery / ...等或任何客户端代码

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

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

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

You should use string.Format in this case. 在这种情况下,您应该使用string.Format。 This is better coding style. 这是更好的编码风格。 For you it would be: 对你来说它将是:

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

Also note that when you should escape " symbol or use apostroph instead. 还要注意,当你应该逃避“符号或使用apostroph而不是。

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

You need to escape your quotes (Take a look at the "Special characters" section). 你需要逃避你的报价 (看看“特殊字符”部分)。 You can do it by adding a slash before them: 您可以通过在它们之前添加斜杠来执行此操作:

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

I use this and it works, as long as the page is not redirect afterwards. 我使用它并且它可以工作,只要页面之后没有重定向。 Would be nice to have it show, and wait until the user clicks OK, regardless of redirects. 很高兴让它显示,并等到用户点击OK,无论重定向。

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

Calling script only can not do that if the event is PAGE LOAD event specially. 如果事件特别是PAGE LOAD事件,则仅调用脚本不能这样做。

you need to call, Response.Write(script); 你需要调用,Response.Write(script);

so as above, string script = "alert('" + cleanMessage + "');"; 如上所述,string script =“alert('”+ cleanMessage +“');”; Response.Write(script); 的Response.Write(脚本);

will work in at least for a page load event for sure. 至少会为页面加载事件工作。

if u Want To massage on your code behind file then try this 如果你想要按照你的代码隐藏文件然后试试这个

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

popupScript += "</";
popupScript += "script>";
Page.RegisterStartupScript("PopupScript", popupScript);

you can use following code. 你可以使用以下代码。

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

The quotes around type="text/javascript" are ending your string before you want to. type =“text / javascript”周围的引号在你想要之前结束你的字符串。 Use single quotes inside to avoid this problem. 在里面使用单引号可以避免此问题。

Use this 用这个

type='text/javascript'

尝试:

string script = "<script type=\"text/javascript\">alert('" + cleanMessage + "');</script>";
 <!--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 -->

its simple to call a message box, so if you want to code behind or call function, I think it is better or may be not. 它简单地调用一个消息框,所以如果你想要编写代码或调用函数,我认为它更好或者可能不是。 There is a process, you can just use namespace 有一个过程,你可以只使用命名空间

using system.widows.forms;

then, where you want to show a message box, just call it as simple, as in C#, like: 那么,你想要显示一个消息框,只需将其称为简单,就像在C#中一样,如:

messagebox.show("Welcome");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM