Click here to Skip to main content
Click here to Skip to main content

AJAX Enabled MessageBox

By , 14 Sep 2009
 

Introduction

As you know, MessageBox, I mean showing popup messages to users is not hard, but there are some complicated issues in web applications because there is no "MessageBox.Show(...)" option in ASP.NET. Inshallah, at the end of this article we will have a similar one.

Using the Code

To get a better idea about our purpose, here is the list of features of the MessageBox that we will generate:

  • The MessageBox should have a simple usage. We should show the message with such a single line of code.
  • The MessageBox should be modal. I mean, a user should not be able to do any other operation while the message is open.
  • The MessageBox should support multiple messages. Multiple messages may be shown through one postback.
  • The MessageBox should have a different appearance according to the type of the message, whether it is an error message or just an information message.
  • The MessageBox should have confirmation functionality.
  • The MessageBox should be AJAX ready.

Now we know what we need and let's analyze how it works.

The MessageBox will be a usercontrol and can be used by adding to the page or to another usercontrol. A simple drag and drop operation.

First we need a message class. Message class is a simple class, having only two properties which are MessageText of string type and MessageType of enmMessageType type. enmMessageType has four items: Error, Success, Attention and Info.

The usercontrol has a method named AddMessage(). This method has two overloads:

public void AddMessage(string msgText, enmMessageType type){....}        
public void AddMessage(string msgText, 
	enmMessageType type, bool postPage, bool showCancelButton, string args){...}

Another important thing about this usercontrol is that it is AJAX enabled. All the contents of the usercontrol are inside an UpdatePanel named udpMsj which has an UpdateMode of Conditional. And OnPreRender state of the usercontrol if any message is added, the UpdatePanel is updated by calling the Update() method. In this way, the content is refreshed only if it is needed.

I will not describe these methods and any other parts of the usercontrol any more, instead I will show the usage of these methods and this will make things precise.

1. Simply Showing A Message

protected void btnInfo_Click(object sender, EventArgs e) 
{     
     uscMsgBox1.AddMessage("The user saved successfully but should be activated 
	by an administrator within 3 days.", 
	YaBu.MessageBox.uscMsgBox.enmMessageType.Info); 
}

This will show the following message:

InfoMessage

Simply by changing the second parameter of the AddMessage method which is YaBu.MessageBox.uscMsgBox.enmMessageType.Info, the message will have a different appearance as shown below.

When the MessageType is set to ERROR:

ErrorMessage

When the MessageType is set to ATTENTION:

AttentionMessage

When the MessageType is set to SUCCESS:

SuccessMessage

2. Show Multiple Messages at a Time

protected void btnMultiple_Click(object sender, EventArgs e) 
{ 
     uscMsgBox1.AddMessage("The user saved successfully.", 
		YaBu.MessageBox.uscMsgBox.enmMessageType.Success);
     uscMsgBox1.AddMessage("The newly saved user account should be 
		activated by an administrator within 3 days", 
		YaBu.MessageBox.uscMsgBox.enmMessageType.Attention);
}

When multiple messages are added:

MultipleMessages

3. Show Confirmation Message

And lastly, we can use it to get confirmation. But this is not as simple as the above ones:

protected void Page_Load(object sender, EventArgs e)
{
     uscMsgBox1.MsgBoxAnswered += MessageAnswered;
}
protected void btnConfirm_Click(object sender, EventArgs e)
{
     uscMsgBox1.AddMessage("Do you confirm to save a new user?.", 
	YaBu.MessageBox.uscMsgBox.enmMessageType.Attention, true, true, txtArg.Text);
}
public void MessageAnswered(object sender, YaBu.MessageBox.uscMsgBox.MsgBoxEventArgs e)
{
     if (e.Answer == YaBu.MessageBox.uscMsgBox.enmAnswer.OK)
     {
          uscMsgBox1.AddMessage("You have just confirmed the transaction. 
		The user saved successfully. You have entered " + txtArg.Text + 
		" as argument.", YaBu.MessageBox.uscMsgBox.enmMessageType.Info);
     }
     else
     {
          uscMsgBox1.AddMessage("You have just cancelled the transaction.", 
				YaBu.MessageBox.uscMsgBox.enmMessageType.Info);
     }
}

The first messagebox for confirmation looks like:

Confirm1Message

And the second one after the user's answer looks like this:

Confirm2Message

That's all, enjoy it. A simple application is attached to this article.

History

  • September 15 2009: First release

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Yavuz Küçükpetek
Software Developer (Senior) NetCad
Turkey Turkey
Yavuz is a software developer since 2001 and working as senior software developer at NetCad in Ankara, Turkey.
 
He has experience in mostly Microsoft technologies such as ASP.Net, SQL Server, C#, VB.Net, WPF, WCF etc. and especially interested in security and performance issues.
 
He also writes articles both in Turkish and English at:
http://www.dotnetgurus.net

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionRe: doesn't work with the AjaxControlToolKit version 3.0.30512.1memberyhfcn22-Oct-09 16:04 
Sorry, I have made a confusion. Your demo code use the ajaxcontrol tool kit.dll version:3.0.20820.16598. But currently my project use the Version:3.0.30512.20315.
 
When I use Version:3.0.30512.20315, then debug the page, show an
"Error 4 Could not load file or assembly 'AjaxControlToolkit, Version=3.0.20820.16598, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) C:\InfoManageSystem\MessageBoxUsc\uscMsgBox.ascx 1 "
 
Can you give me a demo sample code that use Version:3.0.30512.20315?
thank you very much.
 
best regards,
Mike
AnswerRe: doesn't work with the AjaxControlToolKit version 3.0.30512.1memberYavuz Kucukpetek22-Oct-09 9:43 
hi,
 
I have just used the sample project with both versions 3.0.30512 and 3.0.30930.28736 but didn' t see the 3.0.820.0 version in codeplex.
 
Here is the process of how to change the ajaxcontroltoolkit version
 
- Delete the toolkit reference from the project's references part,
- Delete the dll both in the root and bin directory
- Place the new dll in the root and then add reference to this dll by browsing in the Add Reference window
- For the last in web.config replace the existing add assembly line with the appropriate one below according to the version
<add assembly="AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
<add assembly="AjaxControlToolkit, Version=3.0.30512.20315, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
 
I hope it helps, if it does not Smile | :)
- Clean the C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files directory by deleting the files folders
- Close all the browsers and execute gacutil /cdl command in the Visual Studio 2008 Command Prompt
QuestionRe: doesn't work with the AjaxControlToolKit version 3.0.30512.1 [modified]memberyhfcn22-Oct-09 18:11 
I use AjaxControlToolKit version 3.0.30512.1, then build,show the error below,
 
Error 3 Could not load file or assembly 'AjaxControlToolkit, Version=3.0.20820.16598, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) C:\InfoManageSystem\MessageBoxUsc\uscMsgBox.ascx 1
 
can you update the demo code use AjaxControlToolKit version 3.0.30512.1. or Version=3.0.30930.28736 ?

thank you
 
modified on Friday, October 23, 2009 4:48 AM

AnswerRe: doesn't work with the AjaxControlToolKit version 3.0.30512.1memberYavuz Kucukpetek23-Oct-09 11:20 
hi
 
I have prepared a demo using version 3.0.30512 but as I said before here it is a problem to update the article or the attached files.
you can find it here,
 
http://www.dotnetgurus.net/post/2009/09/15/ASPNet-MessageBox-with-AJAX.aspx[^]
 
At the bottom of the page you can download the new demo with the new version. Also this one includes both vb.net and c# projects.
GeneralRe: doesn't work with the AjaxControlToolKit version 3.0.30512.1memberyhfcn23-Oct-09 14:06 
Everything is done with the new version. You help me solve a big problem. Now I look at everything is nice. Big Grin | :-D
Thank you very much! I vote 5, It's really a great job.
 
By the way, if There is a ajaxcontroltoolkit.dll with new version will be published in the future, Can I take place of the old one myself? If yes, I think this messagebox will be much better and more helpful.
GeneralGood ContributionmemberMurat Firat21-Oct-09 4:53 
got my 5.
Thanks for sharing
Questiondo you have the code in vb?memberluperga17-Oct-09 15:54 
hi yavuz, good work Smile | :) do you also have the code in vb? pls share with us, thanks.
AnswerRe: do you have the code in vb?memberYavuz Kucukpetek19-Oct-09 11:29 
hi luperga,
 
I have just converted the attached project to VB.NET. But I cannot find how to add the new project Smile | :)
 
Does anybody know how to attach a new file, I think after some time the article becomes readonly ha ?
AnswerRe: do you have the code in vb?memberYavuz Kucukpetek19-Oct-09 11:42 
hi again,
 
I hope it is not illegal but I could not find anyway to attach another file, perhaps because of being tired-it is 00:30 AM in Turkey Smile | :)
 
I have uploaded the sample project including both c# and vb.net projects to my blog site. You can get it from http://www.dotnetgurus.net/post/2009/09/15/ASPNet-MessageBox-with-AJAX.aspx[^]
 
By the way for habibsatti Smile | :) the new sample also includes a sample page with a master.
GeneralNice WorkmemberSing Yuen Yip14-Oct-09 4:59 
A very nice design, thank you for sharing your idea.Thumbs Up | :thumbsup:
QuestionError While using master pagememberhabibsatti14-Oct-09 4:11 
Nice work but it gives error "invokeViaServer method not found" while using master pages.
AnswerRe: Error While using master pagememberYavuz Kucukpetek19-Oct-09 11:33 
Hi habibsatti,
 
I have tried the usercontrol in a web content page but did not face to a problem.
 
Could you give some more detail also some code would be useful Smile | :)
GeneralRe: Error While using master pagememberhabibsatti19-Oct-09 18:13 
Hi Yavuz Kucukpetek
 
Thanks for your reply, i have solved my problem basically it was not a master page problem.
GeneralVery NicemvpPaul Conrad12-Oct-09 16:31 
Very nicely done.
 
"The clue train passed his station without stopping." - John Simmons / outlaw programmer
 
"Real programmers just throw a bunch of 1s and 0s at the computer to see what sticks" - Pete O'Hanlon
 
"Not only do you continue to babble nonsense, you can't even correctly remember the nonsense you babbled just minutes ago." - Rob Graham


QuestionUsing the MsgBox utility to a web site projectmemberronziv6-Oct-09 11:04 
Hi Yavuz,
 
Thank you for the good work!!!
I am new to ASP.NET and had difficulties using your message box utility (I created a web site project in VS 2008 for testing your utility)
Can you please explain, step by step how to integrate your message box in a web site project?
Thank you,
Ziv
AnswerRe: Using the MsgBox utility to a web site projectmemberYavuz Kucukpetek7-Oct-09 4:44 
Hi ronziv,
 
Here are the steps I hope I do not bypass any Smile | :)
 
1. Make your web site project AJAX enabled
2. Reference the AjaxControlToolkit(dll) library.
3. Organize your web.config for controltoolkit as
<compilation debug="true">
<assemblies>
.......
<add assembly="Pamukkale.WebControls" />
</assemblies>
</compilation>
 
<pages>
<controls>
<add tagPrefix="AjaxControls" namespace="AjaxControlToolkit" assembly="AjaxControlToolkit"/> </controls>
</pages>
 
add the underlined lines to the appropriate config sections.
 
4. Add a usercontrol to your project and name it for example uscMessageBox. And copy and paste the aspx and cs code from the messagebox control in project which is attached to the article.
PS: Be carefull not to break down the original usercontrol that you added. I mean through the copy paste process do not copy and paste all the page of code (aspx and the cs parts). Copy and paste part by part Smile | :)
 
5. Drag and drop the control to the page that you want to give messages.
GeneralRe: Using the MsgBox utility to a web site projectmemberronziv8-Oct-09 1:44 
Hi Yavuz,
 
Thanks for the quick response and for the helpSmile | :)
 
I have done steps 1-4 and got the error message when compiling :
"Could not load file or assembly 'Pamukkale.WebControls' or one of its dependencies. The system cannot find the file specified."
 
Do you have any idea how to solve this issue?
 
BTW - i also added the folder App_Themes to the project (but it has nothing to do with the error msg, as i added it later).
Ziv
Generalcool work...membermerih5-Oct-09 19:40 
Hi Yavuz,
it's really a nice work. thanks...
AnswerYashiasan sanimemberhamzehlou.mehdi21-Sep-09 23:32 
Betaridi saghol sani Allah sani sakhlasin
GeneralNice article, but...memberDinesh Mani16-Sep-09 21:16 
The article and the solution proposed is good. I had previously done something similar using a seperate page for message and showing the page but it was a pain to invoke it. I mean, I had to write a lot of code to invoke the page and handling the result also required more coding. This is much clean and looks simple to invoke.
 
The article would have been even better had you shared more details about the class than just the output. I know that we can download the source and view the code but its always better if the author explains why s/he has made a particular choice.
 
BTW, I'm a little curious about how you made the prompts modal. As far as my Ajax experience goes ajax prompts can be ignored by clicking on the main page area. Im yet to check the sourcecode and wouldn't be able to do it anytime soon, hence posting this question.
 
Anyway congrats once again on a solution well done!! 4* from me. Smile | :)
GeneralRe: Nice article, but...memberYavuz Kucukpetek16-Sep-09 22:06 
Hi Dinesh Mani,
 
Execuse me for this little detailed article. But to say the truth, I prepared the sample application almost 2 months ago and could not post it because the lack of the article's itself.
 
My C# is better than my english; therefore, I changed my mind and said, I cannot deprive mankind of this messagebox because of a unwritten article Laugh | :laugh:
 
But you are right. I had better to write it more detailed.
 
After all, coming to your question. The modal pop-up namely the messagebox is modal with the help of the css classes.
Please look at the App_Themes\default\default.css file. There you will see /* Modal Popup CSS*/ part.
The css classes of .mpBg, .mp are responsible of the modalness.
 
The pnlMsg control in the uscMsgBox UserControl uses the css class of mp. And the actual actor of the being modal is the mpBg css class. And it is used by ModalPopupExtender mpeMsg's BackgroundCssClass.
GeneralRe: Nice article, but...memberDinesh Mani16-Sep-09 23:04 
I'll check the code at the earliest possible. Thank you! Smile | :)
GeneralSuper....memberJitku16-Sep-09 11:50 
This is really cool post.. Thanx
QuestionWhy not using simple javascript like: window.alert, window.confirm?memberDrABELL16-Sep-09 11:19 
Hi Yavuz,
 
Just wondering what is the key advantage of proposed solution vs. simple javascript pop-ups like window.alert, window.confirm, window.prompt?
 
IMHO, using AJAX just for this purpose looks like a bit "overdo".
 
Kind regards,
 
Alex
AnswerRe: Why not using simple javascript like: window.alert, window.confirm?memberYavuz Kucukpetek16-Sep-09 20:25 
Hi DrABELL,
 
You are right we can use alert, confirm, prompt functions. The reasons to this solution are;
- Apperance. As you know those pop-ups have a dummy apperance and you cannot change it.
- Look and feel   Smile | :) The visitor can easily get the idea about the message. I mean it is an error or something else. According to my experiences when the users (especially the newbies) get a standart gray messagebox they think something bad happened, they broke down something   Laugh | :laugh:
- Server side confirmation. As you see the control supports server side confirmation. Perhaps you can the same result by using window.confirm but it is client-side and you should add extra code to make it server side   Smile | :) Also to handle the confirmation event is also a problem perhaps not a big one but a problem.
 
For example; assume that you want confirmation from the user repeatedly as
* Do you confirm to delete the user ?   [<b>YES</b> | NO]
* The user has some pending transactions therefore he/she cannot be deleted. Do you want to delete the user and all the pending transactions ? [YES| NO]
* etc
 
You can handle this scenario just by a single handler.
<pre>protected void Page_Load(object sender, EventArgs e)
{
      uscMsgBox1.MsgBoxAnswered += MessageAnswered;
}
protected void btnDelete_Click(object sender, EventArgs e)
{
      uscMsgBox1.AddMessage("Do you confirm to delete the user ?", enmMessageType.Attention, true, true, "Step1");
}
public void MessageAnswered(object sender, YaBu.MessageBox.uscMsgBox.MsgBoxEventArgs e)
{
      if (e.Args == "Step1")
      {
               if(e.Answer == YaBu.MessageBox.uscMsgBox.enmAnswer.OK)
               {     
                     bool hasPendingTransactions = bllUser.CheckTransactions(userId)
                     if(hasPendingTransactions)
                     {   uscMsgBox1.AddMessage("The user has some pending transactions therefore he/she cannot be deleted. Do you want to delete the user and all the pending transactions?", enmMessageType.Attention, true, true, "Step2"); return;
                     }
                     else{ // delete user}
               }
               else{ // nothing to do}
      }
      else if (e.Args == "Step2")
      {
               if(e.Answer == YaBu.MessageBox.uscMsgBox.enmAnswer.OK)
               {     
                     // delete user and all the transactions
               }
               else
               {
                     // nothing to do
               }
      }
}</pre>
 

Of course we can find a similiar solution using window.confirm function but isnt this cool Smile | :)
 
As I said before enjoy it   Big Grin | :-D
Good bye

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130617.1 | Last Updated 15 Sep 2009
Article Copyright 2009 by Yavuz Küçükpetek
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid