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

C#Javascriptasp.net

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

Here is an easy way:

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

Solution 2 - C#

string script = string.Format("alert('{0}');", cleanMessage);
if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert")) 
{
    page.ClientScript.RegisterClientScriptBlock(page.GetType(), "alert", script, true /* addScriptTags */);
}

Solution 3 - C#

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

Solution 4 - C#

if you are using ScriptManager on the page then you can also try using this:

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

Solution 5 - C#

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

Solution 6 - C#

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.

Solution 7 - C#

There could be more than one reasons for not working.

1: Are you calling your function properly? i.e.

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)

Solution 8 - C#

ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('ID Exists ')</script>");
          
       

Solution 9 - C#

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

Solution 10 - C#

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

Solution 11 - C#

Try this if you want to display the alert box to appear on the same page, without displaying on a blank page.

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

Solution 12 - C#

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'

Solution 13 - C#

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

Solution 14 - C#

string script = string.Format("alert('{0}');", cleanMessage);     
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "key_name", script );", true);

Solution 15 - C#

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

Solution 16 - C#

try:

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

Solution 17 - C#

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

Solution 18 - C#

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.

Solution 19 - C#

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

Solution 20 - C#

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

Solution 21 - C#

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

Solution 22 - C#

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 = ""; Response.Write(script);

will work in at least for a page load event for sure.

Solution 23 - C#

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

Solution 24 - C#

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

Solution 25 - C#

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

Solution 26 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRG-3View Question on Stackoverflow
Solution 1 - C#Muhammad AkhtarView Answer on Stackoverflow
Solution 2 - C#cemView Answer on Stackoverflow
Solution 3 - C#user2561316View Answer on Stackoverflow
Solution 4 - C#AndrushoView Answer on Stackoverflow
Solution 5 - C#Xtian11View Answer on Stackoverflow
Solution 6 - C#TejsView Answer on Stackoverflow
Solution 7 - C#gbsView Answer on Stackoverflow
Solution 8 - C#Ahmad lahhamView Answer on Stackoverflow
Solution 9 - C#KirstenView Answer on Stackoverflow
Solution 10 - C#Orlando HerreraView Answer on Stackoverflow
Solution 11 - C#jithin johnView Answer on Stackoverflow
Solution 12 - C#R KittyView Answer on Stackoverflow
Solution 13 - C#Adriano CarneiroView Answer on Stackoverflow
Solution 14 - C#Nick KahnView Answer on Stackoverflow
Solution 15 - C#Attaullah KhanView Answer on Stackoverflow
Solution 16 - C#Carlos MView Answer on Stackoverflow
Solution 17 - C#MA9HView Answer on Stackoverflow
Solution 18 - C#Jack SpektorView Answer on Stackoverflow
Solution 19 - C#Silvio MarinoView Answer on Stackoverflow
Solution 20 - C#user2389005View Answer on Stackoverflow
Solution 21 - C#Fandango68View Answer on Stackoverflow
Solution 22 - C#Edwin bView Answer on Stackoverflow
Solution 23 - C#Deepak KushwahaView Answer on Stackoverflow
Solution 24 - C#Tabish UsmanView Answer on Stackoverflow
Solution 25 - C#CodeView Answer on Stackoverflow
Solution 26 - C#Mustafa IqbalView Answer on Stackoverflow