ASP.NET Alerts: how to display message boxes from server-side code?

One of the most common mistakes beginner ASP.NET developers make is to call MsgBox.Show from their ASP.NET server-side code. It is a mistake because this code runs server-side and will just display the message box on the server where it's not going to be very useful. Well, in version 2.0, it will actually throw an exception.

Once the developers understand the disconnected way HTTP works, it becomes quite natural, but the need to trigger an alert box from the server-side remains.

That's why I just published a new GotDotNet workspace CodePlex project that contains an Alert server control and a ConfirmButton server control that you can use both client-side and server-side. The controls should work fine in all browsers, but will look a little nicer in IE thanks to the (non-standard) modal dialog feature.

Here's how you use the controls...

First, if you want to show an alert from server-side code, you've got to first declare the alert in your page's markup (or new up a new Microsoft.Samples.Alert.Alert control and set its properties and subcontrols if you're that sort of developer):

<ms:Alert ID="ServerAlert" runat="server" Buttons="OK" Title="Server Alert" OnChoice="ServerAlertChoice"
Font-Names="Arial" HorizontalAlign="Center" Width="350px" Height
This is a rich alert box that was triggered by<br /><i>server-side code</i>.<br

And then simply call the Show() method on the Alert instance from server-side code:


You can handle the user's choice server-side by handling the OnChoice event and act accordingly:

public void ServerAlertChoice(object sender, AlertChoiceEventArgs e) {
  AlertResult.Text =
"You clicked "
+ e.Result.ToString();
  AlertResult.Visible =

You can also trigger the alert's display client-side and handle its response client-side:

<ms:Alert ID="ClientAlert" runat="server" Buttons="YesNoCancel" Title="Client Alert"
  Font-Names="Arial" HorizontalAlign="Center" Width="350px" Height
  This is a rich alert box that was triggered by<br /><i>client-side code</i>.<br
  The button will take the value that you chose.<br /><br
<input type="button" name="ClientShowButton" value
="Show alert without posting back"
onclick="this.value=<%= ClientAlert.GetShowClientEvent() %>;" /><br />

Or any combination that's useful for you.

You can also use the ConfirmButton as you would use a regular button (it derives from Button) to ask the user for confirmation before posting back to the server:

<ms:ConfirmButton ID="Confirm" runat="server" OnClick="ConfirmClick"
Text="Confirm Button" ConfirmText="Are you sure you want to press this button?" />

And so that you can use such confirm buttons in a repeated control such as a GridView, instances of a repeated confirm button can reference a single alert to save HTML rendering and not repeat the alert text for each data row:

<asp:GridView AutoGenerateColumns="False" DataSourceID="Datasource1"
ID="GridView1" runat="server" DataKeyNames="ID">
<SelectedRowStyle BackColor="gray" />
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True"
SortExpression="ID" Visible="False"/>
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name"/>
<asp:BoundField DataField="Alias" HeaderText="Alias" SortExpression="Alias"/>
<asp:TemplateField HeaderText="Command">
<ms:ConfirmButton ID="Confirm" runat="server"
Alert="GridSelectConfirmAlert" CommandName="select"
Text="Select" /><br />

<ms:Alert ID="GridSelectConfirmAlert" runat="server" Buttons="YesNo" Title="Are you sure?"
Font-Names="Arial" HorizontalAlign="Center" Width="320px" Height="50px">
Are you sure you want to select this row?

Check out the Alert.aspx page for these examples in context.

I hope this is useful. As always, feedback is welcome.

UPDATE: The first release was missing a file. I've corrected the version in source control and the release file. Thanks for pointing that out.

UPDATE 2: the project migrated to CodePlex.

UPDATE 3: Since I wrote this, many things happened, such as Ajax becoming mainstream. You might want to try this extender from the Ajax Control Toolkit:


  • Hi, seems great..

    Will you release this Alert for .NET 1.1? Or are there any limitations why it's not possible?

  • It should be very easy to back-port to 1.1 (probably just change the script registering to the old APIs and recompile). Feel free to do it if you need it.

  • Tried to run sample, fixed the following error, but once I click any button I get Page cannot be found - web page dialog, something is missing hear.

    In the sample file Alert.aspx you forgot to add assembly in the register directive

    &lt;%@ Register Namespace=&quot;Microsoft.Samples.Alert&quot; TagPrefix=&quot;ms&quot; Assembly=&quot;Alert&quot; %&gt;

  • That's true. Sorry about that. It's now fixed.

  • Hi All,

    I'm not too sure if It's just me or VWD Express. But when I try to incorporate this sample in to my application, I can NOT get the 'ms' tag to appear in the intellisense and when I try using &lt;ms:alert&gt;&lt;/ms:alert&gt; tags I get an error &quot;Validation (Internet Explorer 6): Element 'ms' is not supported&quot;

    Basically, I'm taking these steps:

    1. copy the Alert.dll (and I've tried copying everything else as well) to my bin directory.

    2. Then referenced the .dll through the &quot;Add references...&quot; dialogue.

    3. Added the registery directive &quot;&lt;%@ Register Namespace=&quot;Microsoft.Samples.Alert&quot; TagPrefix=&quot;ms&quot; Assembly=&quot;Alert&quot; %&gt;&quot;

    Still can't get it going .... maybe someone can show me the error of my ways.


  • Jackson: Is the problem only in the designer or do you also have a problem at run-time?

  • You may still run the site using CTRL+F5 from VWD. This should start the web site and open a browser on it even if there were compilation errors. Then you can see what happens at runtime.

  • The site won't compile and gives the following errors:

    &quot;Request for the permission of Type 'System.Web.AspNetHostingPermission, System, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.&quot;

    &quot;Element 'Alert' is not a known element. This can occur if there is a compilation error in the website&quot;

    Note: This error is not specific to my application. I opened a new blank project and get the same errors.

    Do you have an email address I can forward a copy of my test project to? Maybe diagnosing the problem will be easier if you can see it, first hand. Cheers.


  • This control does not work properly with Master Pages. The callback from an Alert never fires.

  • Derek: this has been fixed more than six months ago in release 1.0.1 that you can download from here:

    The source code also reflects that change.

  • Derek, you'll need to send me a repro of your problem. I retested this morning with a master page and didn't see a problem.

    Ideally, file a bug here:

  • Alrighty. I contacted you via GotDotNet's system with a URL to download a sample of it. I hope this helps some.

  • The bug is fixed in 1.0.2 that I just uploaded. Thanks for the bug report.

  • hi...i want the code that admin alert that the database is updated or alert the admin ..that user have a compalin....

  • Tariq: can you be a little more explicit about what you're trying to achieve? If you're trying to send mail alerts, you should try to go to

  • You can not compaire it with java script

  • Ronny: I don't have the slightest idea what you're talking about but I'm pretty sure I didn't compare anything to JavaScript in this post. Can you please elaborate?

  • Dear Sir,
    Can you please send the code in VB to my email:

  • Abo: the VB source code is available from the GotDotNet workspace. Just follow the link.

  • Thanks,
    This is an excellent control. I am having problems getting server side code output to display in the pop-up page.

    I set a public string variable based upon a particular error in a If block in VB.NET code-beside, and I have the ALERT control setup to display the variable using an block.

    The message does not display. Does this have to happen at page load time?


  • Eddie: without seeing your code it's hard to say. You can drop me e-mail at bleroy (at and I'll have a look. Try to remove any dependancies from the code and make it as simple as possible, so that I can easily run it. Thanks.

  • Bertrand LeRoy,
    Sorry it took so long to get back to you, I have been swamped.

    I actually figured it out. I had partial rendering on the page and needed to add an update panel with a trigger. It works great now.


  • I can get the control to work but a message comes up and says Page Can Not Be Displayed. I have tired on several test pages and the same thing appears.

    The Popup works as it is supposed to but the text and buttons will NEVER appear a web error comes up saying the page can not be displayed.

    Does anyone have any clues to what I am doing wrong.


  • Keith: without seeing your code it's hard to say. You can drop me e-mail at bleroy (at and I'll have a look. Try to remove any dependancies from the code and make it as simple as possible, so that I can easily run it. Thanks.

  • Keith:
    I found the same problem as you did, and I got to solve it by copying the folder Alert that comes with the source code to the root of my website. Then everything started to work.
    I hope this helps you. Bye.

  • I am somewhat new to the Asp.Net environment. I'd also like to get the VB code but I can't locate it.
    Could you be a little more explicit in your directions where it is. I have looked...



  • Many possible causes to that but the most likely is that you didn't copy the folder that contains the VB code as a web application. So ASP.NET is probably not even looking at the App_Code folder because it's not at the root of an applicaiton.

  • Hi Bertrand, Thanks for the code. I was just wondering whether I can change the location of the "YesNo" button. Because they're next to the other and I would like to add more space, so user won't mistakenly click on the wrong button.

    Other than that.. It works perfectly.

  • Ronny: feel free to modify the code and add more space. Would you need help with that?

  • One more thing, Bertrand.
    Is it possible for the button to check the validation first before confirmation pop up.
    I am using ConfirmButton and when the button is clicked, it doesn't check validation control that I have on the page, even after I use CauseValidation = true.

    Thanks so much

  • Ronny: good point, you'dprobably need to modify the code a little so that it respects the property.

  • Thanks for your quick response, Bertrand. It amazes me..:) I couldn't figure it out how to add space between the button and also for the validation, I am still trying to understand your code..

  • In RenderChildren, just create a bunch of literal controls that contains "&nbsp;" and add them to the list of controls between the buttons.
    The validation thing may be a little trickier, you'd need to change the script that's being registered from Show, depending on the value of the property. You can cheat a little by looking at the code that's being generated by another control that gets it right, like a submit button which causes validation.

  • Thanks Bertrand, I've managed to add more space between the buttons. I am still working to get the button cause the validation.
    Could you tell me how I can see the code that's being generated by submit button?

  • Add a button to the page, make it cause validation, browse to the page, view source.

  • hi,

    probs with alert msgs , when iam using atlas its not working ....i mean popup boxes are not coming ..with out atlas its working if any wrong ...and also me

  • Do you get any script errors?

  • Hi, great control
    but I would love to set the text in the code behind
    is there a way to do it
    something like
    ServerAlert.Text = "message here"

    this way I don't need to hard code the text in the html side

  • Any support for using the ms:confirmbutton w/ a delete imagebutton within a gridview?

  • how to display message boxes from server-side code?

  • resh: I don't quite understand the question, that's exactly what the blog post is about...

  • The message works great except when I put around it, then it does not work.
    Do you know why?

  • Ta: yes, this is a known problem. It currently doesn't work inside UpdatePanel.

  • Hi,
    I shoed alert msg but after pressing button my aspx page get to solve this pblm

  • Kalpesh, what do you mean "expired"?

  • How can I generate msgbox with three buttons Yes/No/Cancle when a user is updating his record.

  • Suraj: the gridview example in the post is almost what you're looking for, except for the cammand name and the buttons, right?

  • Where can I get the ASP.NET Alerts control since the gotdotnet site has been phased out?

  • John: I'm in the process of moving it to

  • Hi, where can I get the source code so I can modify it on .Net 1.1? I works fine on .Net 2.0, but I want to add this feature to my old project. Thanks a lot!

  • Allan: I haven't had time to migrate the source code yet, but I will in the following days. Sorry about the delay.

  • Found the Alert source code still not migrated to codeplex,when can i expect it?

  • Vidya: it's in now. Thanks for your patience.

  • First off, thanks for sharing your time and effort -- a much needed control.

    I've downloaded and run the sample Alert.aspx page and am noticing that it displays all button configurations in IE fine, but in firefox the only thing I can get rendering is "OK / Cancel" or just "OK" regardless if buttons="AbortRetryIgnore", it renders as ok / cancel. Is this just a browser limitation and so to be totally browser compatible I'll have to assume that users are only seeing 2 buttons which might only say "OK / Cancel"?

    Not a terrible thing, but a developers is always concerned with the lowest common denominator. Thanks!

  • Aaron: The control currently uses IE's modal dialog feature, which is not in Firefox. That's why the control downgrades to regular text alerts in this case. Ideally, the control would use a simulation of modal dialog such as the one in the ASP.NET Ajax Control Toolkit but I didn't have time to go that far.

  • Hi, I would like to know if this control works with AJAX.NET inside an AJAX Update Panel.

    Do you know of any workaround to my problem? I was injecting literals to the page with the JS code, but it doesn't work with Updates Panels :(

    Thanks in advance,

  • Marcelo: no, this control was developed way before UpdatePanel and doesn't currently work with it (though I would gladly accept a contribution to the project that makes it work).
    You can read this to learn more about how to make controls work well with UpdatePanel:

  • Hi,
    I am looking to do the following:

    I have a gridview and each row has a checkbox.
    If the user does not check at least one checkbox,
    I want to display an alert message that at least
    one box must be checked.

    Any help would be appreciated.


  • we can create serverside msgbox like


    KeyValue : Give any name to message box

    MessageString : Write down message what do you want to Display

  • C: you forgot the alert(' and '); around the message string and the key is not the name of the message box, it's a name that you use on the server side to be sure not to register the same thing twice.

  • Hi,a many thanks for this control...but can you tell me how if in a gridview there is a commandfield for delete operation(I mean something like this ), I can use your control? I cannot go for an item template & declare an alertbox there(The commandfield delete button is configured with an objectdatasource)....Also the Gridview is declared inside an update panel...thanks in advance....

  • Paul: you'll have to template instead of using a commandfield and specify the delete command name on the template's delete confirmbutton, like in the blog post's example. I'm not sure how using an ObjectDataSource changes anything. On the other hand, the curent version of this control doesn't work with UpdatePanel.

  • Hi, i have been using this control to navigate to a second page. (which happens to be an excel spreadsheet) using response.redirect withing the choice method, the problem i have is when i clich the 'back' browser button the dialog box created stays on the screen. How can i get rid of it and stop it displaying ? i have tried various methods of making it not visible on pre_load init etc.

    PS. This is a great little tool !

  • Nicholas: this may be caused by client-side caching. Did you check if the server gets hit at all by attaching a debugger?

  • I have validation code (related to tolerances which are specified in my database) on the server side which I wanted to use with this alert code. I was able to add in the DLL as a reference to my project and Intelisense detected the reference and what was in it, but when I went to build for the first time after adding some alert code in, I got an error in VS 2005.

    "Assembly Generation Failed: Alert does not have a strong name."

    In my code I was constructing an alert by the second method you mentioned (in C# code rather than ASP tags)

  • I don't know. Maybe in order to reference the alert controls from a signed assembly, you need them to be in a signed assembly. You should probably try to compile the alert code into a signed assembly and reference that.

  • Excellent piece of code!
    Your example of setting the text on the dialog didn't wotk, but I nested a label inside the tags:

    This way I can calculate the impact of the users actions, and tell him before he hits the button.
    Works perfectly!
    Many thanks.

  • @Vijay: if you look at the alert.aspx sample page, you'll see an example of that: just handle the OnChoice event, and you'll get an AlertChoiceEventArgs parameter that gives you which button was clicked through its Result property.

  • Hi,

    This is simply superb. But I need to customize the alertbox.
    1. Currently the alertbox can be resized by dragging it. I dont want to resize it.

    2. I want to change the opacity of the page excluding alertbox like the one in ajax control toolkit modal popup.

    3. I dont want the title --Webpage Dialog in the alertbox

    4. I need to add some images in the alertbox.(Example: For an error message ,one image will be shown. For a normal information,some other image will be used)

    Venkatesan J
    Prince of Pammal

  • Venkatesan: those are interesting suggestions, but this code is provided as is. Feel free to implement those if you want to, and I'll be happy to point to your modifications from here.

  • @Lars-Erik: that should be quite easy to achieve by hacking into the code a little. I don't think it will care if your use image inputs instead of buttons.

  • how can i get microsoft.samples.Alert?

  • @arunpulikkan: follow one of the two links in the post to the CodePlex project.

  • The alert box works great when i run my pages in the ASP development server. But when i host it on IIS and try to access the pages, the alert box works fine except for a status bar that gets displayed inside the alert box. Any solution for this problem?

  • @Raj: Do you mean the browser's status bar? Is the browser version the same in both cases?

  • Thanks for your quick response..

    Yes, Roy its the browser's status bar. The browser version is also same in both the cases.

  • @Raj: I don't know where the difference comes from but more and more, browsers don't allow scripts to remove chrome from pop-up windows to avoid phishing attacks that mimic non-browser windows. That may be what's happening here. How much of a problem is this status bar?

  • Its quite a bit of a problem, as we need these to validate the inputs given by the user which can happen from both client as well as server side. Now if an alert box has a status bar, it doesnt look too good.
    Is there any kind of workaround for this problem?

  • @Raj: you could try to use instead.

  • Hi, i am not supposed to use AJAX, any other way to solve this problem other than using ajax?

  • The control in the Ajax Toolkit doesn't really use Ajax, so you might be able to reuse some of the code in there although it might be quite a lot of work. I guess your options would be to live with the status bar, make your own control using techniques similar to what the Toolkit is doing or use the toolkit.

  • hmmm. not left with that much time i guess. Let me see if i can do something about it. If i get any solution, will post it here. Thanks a lot for your help.

  • How can I use the Alert.dll in VS2003, when I try to add a reference to it i get an error message saying

    "A reference to XXX could not be added. This is not a valid assembly or COM component. Only assemblied with extension 'dll' and COM components can be referenced. Please make sure that the file is accesible and that it is a valid assembly or COM component"

    Using .Net 1.1

  • @Vaishali: 1.1? Wow. that's old. Sorry, this is compiled against 2.0.

  • Added the Alert control to my project without issues, and it compiles fine, but when I trigger the .Show() method, the message box opens with an HTTP 404 in it, instead of the specified HTML.

    I use Master Pages for my layout, if that makes any difference (downloaded it today from codeplex so I should have the latest version).

    Any ideas?

  • @Alex: you forgot to copy the alert/displayalert.htm file to your site.

  • Bertrand I put this in my website and it works perfectly. I just have one problem that I am sure is my own lack of understanding. I have a central utility that carries out actions and posts various alerts if something goes wrong. The error message is passed as a string from server side code of the page to the server side code of the utility. I managed to get the utility to post the alert by using 'Imports Microsoft.Samples.Alert' but I can't find a way to get the error message string into the alert. There are many text options on the Alert Object like ServerAlert.Title or ServerAlert.OKText but there doesn't seem to be a ServerAlert.MessageText I noted in the html you have 'This is a rich alert box that was triggered by
    server-side code' I am guessing that I can call a serverside proceedure between the 's to supply text but I don't know the syntax or how.

  • @Sean: haven't touched that code in a while, but from the top of my head, the control uses its own contents as the text of the alert, so if you add a literal control to it with your message, it should work.

  • Bertrand: I put a label inside the alert, passed the label to my utility, set label.text = 'error message string' and it worked perfectly. I feel a little dumb looking for long programatic solutions when like you pointed out the alert contents can be set up like any html page. Thank You for the help and the very usefull control.

  • Couldn't get ConfirmButtonExtender/ModalPopupExtender/Validation to work together. Luckily, I found this site. Anyway,
    This works great but lyon IE. On FireFox, the message box doesn't show anything but the word "undefined" How can I can fix this? Thanks.

  • @hanvo: this is a very old project that would be done completely differently today. Feel free to use an modify the code, but I'd encourage you to use the ACT controls instead, and file bugs there for issues you find.

  • how to put links inside a grid that has been retrieved and build from an xml file

  • @a^n: I don't know, you should ask that question on a forum that has something to do with your question instead of doing it on random blog posts. For example,

  • i very crazy about this

  • Great job. Perfect match for my problem - some server side processing, then a confirm/alert box, followed by more server side processing. One question: how to remove "--Webpage Dialog" from the Title?

  • Hi. get the same problem as Jackson. only I know it isn't an environment issue because as soon as i remove the asp code (<ms:Alert ID="ServerAlert"...) I can run everything as usual. Am I missign sometyhing here? Help is greatly appreciated..

  • @Lolo: you're probably missing a @register directive on you page.

  • I want show a message box which will first confirm if i click ok it wil redirect me to next page.

  • Sorry I didn't see the Leave a Comment form so I sent this first to your Contact page.
    Bertrand, I too am unable to use Alert.
    I copied Alert.aspx to my project folder and then copied Alert.dll to C:\Program Files\Microsoft Visual Studio 10.0\VB\Bin.
    Is that the correct Bin folder? If not, what is the correct folder?
    Sorry to bang on about your second least favourite subject, judging by 'Mandatory look back at 2010', but I'm new to ASP.NET, which has raised my opinion of Microsoft very considerably. I had my first, and real, production site up and running in a very short time, most impressive, but my error alerts kept appearing behind the browser. I had no idea why until I found your article, which appears to be a godsend. Why hasn't Microsoft made Alert an official part of ASP.NET? Everybody needs to notify the user of errors and warnings. Well I'm very glad you made this control, and I thank you but some installation instructions might have been a good idea.

  • @Mike: no, that is not the correct bin folder. 99% of the time, when people are talking about the bin folder, they are talking about the bin folder that is immediately under your web application's root folder.
    One of the many reasons why this is not in the framewrok is that frankly there are much better ways to do notifications on the web than dialog boxes. For example, have a notification area on top of your page.

  • Thanks Bertrand, now it does exactly what it says on the tin! Many thanks.

  • Great idea, but couldn't get past Microsoft JScript runtime error: 'WebForm_PostBackOptions' is undefined. Only httpmodule I had was "ScriptModule". Under pressure to finish a project; have to find another way to solve this.

  • @Bruce: this code is antique. You should consider using more modern alternatives, such as jQueryUI.

Comments have been disabled for this content.