简体   繁体   中英

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

I am reading this JavaScript: Alert.Show(message) From ASP.NET Code-behind

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

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

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

These are two ways to display alert messages in c# code behind

如果您在页面上使用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

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? ie

Repository.Show("Your alert message");

2: Try using RegisterStartUpScript method instead of scriptblock.

3: If you are using UpdatePanel, that could be an issue as well.

Check this(topic 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

Step 1 Add your Javascript code

<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

Step 3 Add this code in your button click event

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

// 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

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

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

You should use string.Format in this case. 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.

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.

/// <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.

you need to call, Response.Write(script);

so as above, string script = "alert('" + cleanMessage + "');"; Response.Write(script);

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. 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:

messagebox.show("Welcome");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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