[c#] 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?

This question is related to c# javascript asp.net

The answer is


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

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

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

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


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

string script = string.Format("alert('{0}');", cleanMessage);     
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "key_name", script );", 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

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

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

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


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

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


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)


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

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.


try:

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

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

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

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'

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.


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

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

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery