KARPACH

WEB DEVELOPER BLOG

Javascript Alert Message from code behind in ASP.NET

How to show a javascript alert message from a code-behind? You probably know, that we can do it like this:

ClientScript.RegisterStartupScript(Page, "message", "alert('Hellow world!');", true).

However, this method is not going to work in AJAX environment. For AJAX you need to use: ScriptManager.RegisterStartupScript.Here is a little utility method, which displays a javascript alert message both in AJAX environment and on a regular page:

public static void ShowAlertMessage(string error)
{
    Page page = HttpContext.Current.Handler as Page;
    if (page != null)
    {
        error = error.Replace("'", "'");
        ScriptManager.RegisterStartupScript(page, page.GetType(), "err_msg", "alert('" + error + "');", true);
    }
}
Posted on March 19, 2008 by

Comments

Posted on 7/25/2008 10:00:47 PM by Malik

can’t get the page value from the following line Page page = HttpContext.Current.Handler as Page; it always shows null….. wat is d problem….help needed

Posted on 6/17/2009 07:12:10 AM by Arshika

Really nice this is very helpful and easy.

Posted on 8/11/2009 01:53:06 PM by reTkom

This works great, but if i use a response.redirect it doesnt come up, the page just transfers from one page to another without showing the aler, can somebody help please?

Don’t do Response.Redirect. Modify code as follow, so it can do alert and redirect:

ScriptManager.RegisterStartupScript(page, page.GetType(), "err_msg", "alert('" + error + "');window.location='newpage.aspx';", true);

Otherwise you need to pass your message in query string and then on the destination page do ScriptManager.RegisterStartupScript in Page_Load event.

Posted on 2/8/2010 09:44:37 PM by Prabakaran

Hi,

Same problem i have..i having alert script in my code behind. after the alert script i put response.redirect…

It will transferred to new page without showing alert message..

How do i resolve them..

ScriptManager.RegisterStartupScript(page, page.GetType(), "err_msg", "alert('" + error + "');window.location='newpage.aspx';", true); 

Posted on 2/9/2010 12:07:33 AM by Prabakaran

ScriptManager.RegisterStartupScript(page, page.GetType(), "err_msg", "alert('" + error + "');window.location='newpage.aspx';", true);

The window.location not work..but the alert message is shown

Does it give javascript error? Try to specify absolute path.

Posted on 2/9/2010 10:07:36 AM by Luo Long

Viktar-

After many, many hours of searching for a solution to showing an alert from my C# code behind while implementing AJAX on my HTML page, I finally came across your solution. It works great! Microsoft owes you big time for this easy solution.

Luo Long

Posted on 2/10/2010 10:57:30 PM by hemant

thanks it works for me

Posted on 4/11/2010 11:20:19 PM by Irina

thank you very very mach, I tried to find solutioon for this ussue for a long time, and this one so simple and elegant!!

Posted on 4/26/2010 12:23:24 AM by Sudheer

Really nice this is very helpful and easy.

Posted on 6/29/2010 01:06:06 PM by Jerry Elbow

Thanks, this did the trick for me. Other approaches I tried either painted the alert box against a blank background or against a web page that hadn’t finished drawing or else actually messed up the web page. This one worked perfectly.

Posted on 7/28/2010 12:00:16 AM by Shakti Raturi

Grt ……..its working…….

thnak u……….

Posted on 9/8/2010 06:09:39 AM by ross

this is the absolute business!!! thank you soo much for this post!!!

Posted on 9/10/2010 06:42:14 AM by ilavarasan Elango

it’s realy nice ,go ahead buddy.

Posted on 11/10/2010 09:10:49 AM by Petter

Hi,

Thanks for this great piece of code. Here it is for VB.Net (had to change it somewhat as some variable names are not allowed in VB.Net). I put it in a class that all my pages inherit (see below if you’re new to that).

/Petter

The code, in a class called Mainclass, in the App_Code folder:

  Public Shared Sub ShowAlertMessage(ByVal msg As String)  
        'Display javascript-alert  
        Dim page As Page = TryCast(HttpContext.Current.Handler, Page)  

        If page IsNot Nothing Then  
            msg = msg.Replace("'", "\")  
            ScriptManager.RegisterStartupScript(page, page.GetType(), "err_msg", "alert('" & msg & "');", True)
        End If
    End Sub

Top of the .aspx.vb page:

Imports Mainclass

Calling the code:

ShowAlertMessage("You are now registered.")

Posted on 11/16/2010 01:02:15 AM by Srikanth

great work,keep it up………..

Posted on 12/7/2010 03:05:09 AM by KB

Good one, It worked.

Posted on 1/28/2011 10:45:35 PM by Mustafa t

Very nice code…

thanks a lot…

Posted on 2/18/2011 01:44:01 AM by Maya

Hey Thanx a lot:) it wz qyt helpful :)

Posted on 3/30/2011 10:15:38 AM by asasdasd

THANK YOU!!!!!!!!

THANK YOU!!!!!!!!

THANK YOU!!!!!!!!

Posted on 4/27/2011 05:01:09 AM by Shikhar

Thanks….

It’s Works..

Posted on 5/21/2011 03:42:46 AM by sandhya

Thnxxxxxxxxxxxx a lot….

It solved my problem.

Previously scriptmanager was not working when type is taken as page.

“Page page = HttpContext.Current.Handler as Page;” this line solved my problem…..

Posted on 5/24/2011 08:25:15 AM by CPULI

thanks a lot

Posted on 6/30/2011 10:20:18 PM by siva

Error 1 The name ‘ScriptManager’ does not exist in the current context

Posted on 7/12/2011 10:05:32 PM by Shantanu

Thanks alot…really its very helping

Posted on 7/14/2011 12:35:19 AM by Pardeep kumar

thanks sir, i get it in my first search,thanks alot

Posted on 7/19/2011 03:55:21 AM by Subhash Pande

Hello Sir

Thanks for such a nice piece of code. It really help me in my program.

Thanks alot

Subhash

Posted on 8/26/2011 08:55:41 AM by mark grizzle

Well done!

Posted on 10/5/2011 01:11:29 AM by neeta

Thank you much, this script worked for me.

Posted on 10/7/2011 01:44:15 AM by Bhavya

How can i get the result of confirm?

Posted on 10/7/2011 01:57:30 AM by Bhavya

This code is working. But if we use this code on the page having a menu control , its not working properly.

Posted on 10/14/2011 03:25:29 AM by Lin

Your code is very nice. Working Fine.Thank You.

Posted on 10/28/2011 12:16:05 AM by Vibhu

Thanks for the help Prabakaran

Posted on 11/13/2011 09:04:40 PM by himanshu

Thanks alot !!!!!

thank u very much!!!

:)

Posted on 11/23/2011 05:06:56 AM by Dorababu

How can i use this visual studio 2005
The same way if this is .NET 2.0 and up.

Posted on 12/7/2011 05:26:28 AM by Dheeraj Upadhyay

thank dear it’s works thank’s lot…

Posted on 12/22/2011 07:00:09 AM by lalit

How can change Title of message window???
It is not possible

Posted on 12/23/2011 04:06:44 AM by Mini

hi..i want to know how to display ok cancel alert box
Use javascript confirm command.

Posted on 1/10/2012 03:58:46 AM by Sunil Kanojiya

thanxxx dear,,,, you have saved my tons of time.

Posted on 2/2/2012 01:19:53 AM by Yuva

It works great. Thanks for your solution

Posted on 2/4/2012 11:39:04 AM by Afridi

Excellent Post.

I was looking to show msgbox when user do not enter data..especially with ajax it works greate

Thanks Lot…

Posted on 2/6/2012 10:13:12 AM by K.Bala

Good one,

Am searching for long time..

Thanks

MH,IN

Posted on 3/14/2012 10:00:26 AM by kalpesh thakor

it works after the page design completely loaded…

but my goal is to check whether the session is null or not then the want to show alert and then redirect…

but this soln…shows design in backgroud when it is showing alert…

You need to use AJAX for this. Try jQuery ajax it is the easiest way.

Posted on 3/27/2012 06:14:10 AM by Lakshmi

This is excellent. It really helped me.

Posted on 5/10/2012 07:12:47 AM by Harshal Yelpale

Excellent. It works fine.

Posted on 6/1/2012 11:03:10 PM by Sanjay

Really nice…

keep Helping to all…

Posted on 8/1/2012 06:21:23 AM by Chris

Excellent. It works fine. Ty very much

Posted on 8/13/2012 01:15:41 AM by Duff

just to thanks. It’s really helpful

Posted on 8/26/2012 10:37:15 PM by Tanaji Bhanvase

Nice, I really help it. Thanks.

Posted on 9/17/2012 02:20:08 AM by alvin

Thanks. It works but I have a problem here.

I have a image in my webpage, when i call the ShowAlertMessage method the alert box will appear but my image will disappear and after i click on ‘Ok’ it will appear again. How to make the image not disappear?

Thanks

Based on your description it is hard to tell what’s wrong with your page. Do you use javascript to initialize your image source? May be this initialization script runs after ShowAlertMessage. Also it might be a css issue. Make sure that there is enough space for the image. I would assign overflow:hidden to the image container.

Posted on 10/5/2012 01:45:27 AM by john lim

How to break a line?

The below doesn’t work:

Dim cstext As String ="alert('" & "ddd".Replace(vbLf, "") & "xxx".Replace(vbLf, "") & "')"

It displayed dddxxx but I want

ddd

xxx

Dim cstext As String ="alert('" & "ddd".Replace(vbLf, " ") & "xxx".Replace(vbLf, " ") & "')"

or

Dim cstext As String ="alert('" & "ddd".Replace(vbLf, "\n") & "xxx".Replace(vbLf, "\n") & "')"

Posted on 10/9/2012 04:35:54 AM by Ganesh

Thanks very useful, but I have some other different requirement that can I use the same code in asmx web service in catch block to see what error is thrown by the service?

Please do reply.

It depends how you are using this webservice. Webservice doesn’t have any connection to UI by itself. You can pass back error to webservice caller and then display error from there.

Posted on 10/15/2012 02:20:02 AM by john lim

Dear Viktar,

Sorry for the late update! I just return to work!

Thanks for the advice, for some reason, it didn’t work (still display everything in the same line)

The below is my complete code:

Dim csname As String = "PopupScript"
Dim cstype As Type = Me.GetType()
Dim cs As ClientScriptManager = Page.ClientScript
Dim cstext As String = "alert('" & "First Line".Replace(vbCr, "\n") & "Second Line".Replace(vbCr, "\n") & "')"
cs.RegisterStartupScript(cstype, csname, cstext, True)

TIA

John

I just tested new line works in IE7+,Firefox and Chrome. Your replace probably doesn’t work. Try following:

Dim cstext As String = "alert('" & "First Line".Replace(vbCrLf, "\n") & "Second Line".Replace(vbCrLf, "\n") & "')" 

or

Dim cstext As String = "alert('" & "First Line".Replace(vbLf, "\n") & "Second Line".Replace(vbLf, "\n") & "')" 

Posted on 9/3/2014 02:21:19 AM by Chaitanya

you did an awesome job.

After hours of working you solved my issue in a minute.

Thankyou so much

Posted on 3/25/2015 01:37:26 AM by Jp

I want to display long Message….

But it not allowing me to display more than 10 character….

Posted on 11/8/2020 10:58:59 AM by Hewlett

Howdy very nice website!! Guy .. Beautiful .. Amazing ..

I’ll bookmark your site and take the feeds also?

I am happy to find numerous helpful information right here in the

submit, we’d like develop more techniques in this regard,

thanks for sharing. . . . . . credit karma

Posted on 8/11/2023 10:14:30 AM by Sammy Msafiri

Hi

Thanks for the wonderful ideas on javascript vs ASP.NET.

Just wondering. Is there a way i can call javascript alert with YES, CANCEL options and return results in codebehind?

You can use javascript confirm() and then save result in hidden input tag. As an alternative you could call ajax endpoint with the result.