In an asp.net windows forms application, in the C# code behind you can use:
MessageBox.Show("Here is my message");
Is there any equivalent in a asp.net web application? Can I call something from the C# code behind that will display a message box to the user?
Example usage of this: I have a button that loads a file in the code behind. When the file is loaded or if there is an error I would like to popup a message to the user stating the result.
Any ideas on this?
Right click the solution explorer and choose the add
reference.one
dialog box will be appear. On that select(.net)-> System.windows.form
. ImportsSystem.Windows.Forms (vb)
and usingSystem.windows.forms(C#)
copy this in your coding and then writemessagebox.show("")
.'ASP.net MessageBox
'Add a scriptmanager to the ASP.Net Page
try:
Or create a method like this in your solution:
Then you can use it like:
not really. Server side code is happening on the server--- you can use javascript to display something to the user on the client side, but it obviously will only execute on the client side. This is the nature of a client server web technology. You're basically disconnected from the server when you get your response.
As others already pointed out, a message box will be clientside Javascript. So the problem then is how to force a clientside JS message box from the server side. A simple solution is to include this in the HTML:
and to fill this
data
from the server side code-behind:Note that the string value should be a Javascript string, i.e. be a one-liner, but it may contain escaped newlines as
\n
.Now you can use all your Javascript or JQuery skills and tricks to do whatever you want with that message text on the clientside, such as display a simple
alert()
, as shown in the above code sample, or sophisticated message box or message banner.(Note that popups are sometimes frowned upon and blocked)
Note also that, due to the HTTP protocol, the message can only be shown in response to an HTTP request that the user sends to the server. Unlike WinForm apps, the web server cannot push a message to the client whenever it sees fit.
If you want to show the message only once, and not after the user refreshes the page with F5, you could set and read a cookie with javascript code. In any case, the nice point with this method is that it is an easy way to get data from the server to the javascript on the client, and that you can use all javascript features to accomplish anything you like.
Just add the namespace:
to your web application reference or what ever, and you have the access to your:
I tried it and it worked.
Good luck.