RG-3
RG-3

Reputation: 6188

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?

Upvotes: 65

Views: 467343

Answers (26)

Code
Code

Reputation: 739

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

Upvotes: 0

Xtian11
Xtian11

Reputation: 2270

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

Upvotes: 5

Tabish Usman
Tabish Usman

Reputation: 3250

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

Upvotes: 1

Deepak Kushwaha
Deepak Kushwaha

Reputation: 11

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

Upvotes: 1

Edwin b
Edwin b

Reputation: 111

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.

Upvotes: 1

Ahmad lahham
Ahmad lahham

Reputation: 41

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

Upvotes: 4

Attaullah Khan
Attaullah Khan

Reputation: 21

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

Upvotes: 2

Fandango68
Fandango68

Reputation: 4868

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

Upvotes: 1

user2389005
user2389005

Reputation:

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

Upvotes: 1

jithin john
jithin john

Reputation: 572

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

Upvotes: 3

Mustafa Iqbal
Mustafa Iqbal

Reputation: 73

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

Upvotes: -3

Orlando Herrera
Orlando Herrera

Reputation: 3531

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

Upvotes: 3

Kirsten
Kirsten

Reputation: 500

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

Upvotes: 3

user2561316
user2561316

Reputation: 404

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

Upvotes: 19

Andrusho
Andrusho

Reputation: 155

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

Upvotes: 10

Silvio Marino
Silvio Marino

Reputation: 9

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

Upvotes: 1

Jack Spektor
Jack Spektor

Reputation: 1117

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.

Upvotes: 1

MA9H
MA9H

Reputation: 1909

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

Upvotes: 1

Muhammad Akhtar
Muhammad Akhtar

Reputation: 52241

Here is an easy way:

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

Upvotes: 130

Nick Kahn
Nick Kahn

Reputation: 20078

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

Upvotes: 2

gbs
gbs

Reputation: 7266

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)

Upvotes: 4

cem
cem

Reputation: 1911

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

Upvotes: 24

Adriano Carneiro
Adriano Carneiro

Reputation: 58615

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

Upvotes: 2

Carlos M
Carlos M

Reputation: 81

try:

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

Upvotes: 1

Tejs
Tejs

Reputation: 41236

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.

Upvotes: 4

R Kitty
R Kitty

Reputation: 176

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'

Upvotes: 2

Related Questions