32

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?

Baxter
  • 5,033
  • 21
  • 64
  • 104

14 Answers14

68

You want to use an Alert. Unfortunately it's not as nice as with windows forms.

ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + myStringVariable + "');", true);

Similar to this question here: http://forums.asp.net/t/1461308.aspx/1

Gage
  • 7,067
  • 9
  • 44
  • 77
  • 1
    What is myStringVariable?? – whoadityanawandar Mar 23 '13 at 05:11
  • 3
    myStringVariable is just a string. It would be set to the message you wish to display. – Gage Mar 25 '13 at 20:02
  • @Gage When the message box opens following the event being triggered, the user is presented with an 'OK' button. Is there anyway to wire up a Response.Redirect("desired/path.aspx"); to this? – JsonStatham Jul 25 '14 at 14:30
  • When I try this I just get `No overload for method 'RegisterStartupScript' takes 4 arguments` – Bassie Jul 07 '16 at 10:34
  • If you want to use several messages from a web page you should name them diferently, for example myalert1, myalert2, etc. If your message contains single quotes ', it will not work, you have to replace it by other character, for example |. – Sergio Prats Jul 07 '17 at 15:21
16

Or create a method like this in your solution:

public static class MessageBox {
    public static void Show(this Page Page, String Message) {
       Page.ClientScript.RegisterStartupScript(
          Page.GetType(),
          "MessageBox",
          "<script language='javascript'>alert('" + Message + "');</script>"
       );
    }
}

Then you can use it like:

MessageBox.Show("Here is my message");
Ali Humayun
  • 1,582
  • 1
  • 13
  • 11
  • I get "Extension Method must be static." Any idea? – usefulBee Apr 13 '15 at 17:13
  • 1
    @usefulBee: You forgot to add `static` between `public` and `void`. – Heinzi Mar 17 '17 at 14:23
  • 1
    No exactly true. The class creates an extension metod to a Page object. You either call it using a page instance: this.Show("Here is my message") or supply the page as a parameter: MessageBox.Show(this, "Here is my message") – flodis Sep 15 '17 at 08:37
  • yeah but when you are working in own page class. Then you are not required to use this statement – Ali Humayun Sep 15 '17 at 18:55
10

Just for the records.

Here is a link from Microsoft that I think is the best way to present a MessageBox in ASP.Net

Also it presents choices like Yes and NO.

Instructions on how to get the class from the link working on your project:

  1. If you don't have an App_Code folder on your Project, create it.
  2. Right click the App_Code folder and create a Class. Name it MessageBox.cs
  3. Copy the text from the MessageBox.cs file (from the attached code) and paste it on your MessageBox.cs file.
  4. Do the same as steps 2 & 3 for the MessageBoxCore.cs file.
  5. Important: Right click each file MessageBox.cs and MessageBoxCore.cs and make sure the 'Build Action' is set to Compile
  6. Add this code to your aspx page where you want to display the message box:

    <asp:Literal ID="PopupBox" runat="server"></asp:Literal>
    
  7. Add this code on you cs page where you want to decision to be made:

    string title = "My box title goes here";
    string text = "Do you want to Update this record?";
    MessageBox messageBox = new MessageBox(text, title, MessageBox.MessageBoxIcons.Question, MessageBox.MessageBoxButtons.YesOrNo, MessageBox.MessageBoxStyle.StyleA);
    messageBox.SuccessEvent.Add("YesModClick");
    PopupBox.Text = messageBox.Show(this);
    
  8. Add this method to your cs page. This is what will be executed when the user clicks Yes. You don't need to make another one for the NoClick method.

    [WebMethod]
    public static string YesModClick(object sender, EventArgs e)
    {
        string strToRtn = "";
        // The code that you want to execute when the user clicked yes goes here
        return strToRtn;
    }
    
  9. Add a WebUserControl1.ascx file to your root path and add this code to the file:

    <link href="~/Styles/MessageBox.css" rel="stylesheet" type="text/css" />
    <div id="result"></div>
    <asp:ScriptManager runat="server" ID="scriptManager" EnablePageMethods="True">
    </asp:ScriptManager>  //<-- Make sure you only have one ScriptManager on your aspx page.  Remove the one on your aspx page if you already have one.
    
  10. Add this line on top of your aspx page:

    <%@ Register src="~/MessageBoxUserControl.ascx" tagname="MessageBoxUserControl" tagprefix="uc1" %>
    
  11. Add this line inside your aspx page (Inside your asp:Content tag if you have one)

    <uc1:MessageBoxUserControl ID="MessageBoxUserControl1" runat="server" />
    
  12. Save the image files 1.jpg, 2.jpg, 3.jpg, 4.jpg from the Microsoft project above into your ~/Images/ path.

  13. Done

Hope it helps.

Pablo

Pabinator
  • 1,479
  • 1
  • 20
  • 22
  • 1
    This worked for me, and it's officially an MS solution anyway. – Fandango68 Nov 04 '14 at 04:00
  • Getting Parser Error Message: Could not load type 'CSASPNETMessageBox.MessageBoxUserControl'. – mappingman Mar 02 '18 at 19:46
  • This solution seemed perfect for my issue... until I clicked on the links and found they no longer work (thanks Microsoft!). Can anyone post the code for the MessageBox.cs and MessageBoxCore.cs in steps 3 and 4? Or give me a hint what that code should look like? – samp Oct 15 '20 at 16:53
2

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.

ek_ny
  • 9,877
  • 5
  • 42
  • 57
2

There are several options to create a client-side messagebox in ASP.NET - see here, here and here for example...

Yahia
  • 67,016
  • 7
  • 102
  • 131
2

Why should not use jquery popup for this purpose.I use bpopup for this purpose.See more about this.
http://dinbror.dk/bpopup/

Shree
  • 18,997
  • 28
  • 86
  • 133
1

'ASP.net MessageBox

'Add a scriptmanager to the ASP.Net Page

<asp:scriptmanager id="ScriptManager1" runat="server" />

try:

{

  string sMsg = "My Message";

  ScriptManager.RegisterStartupScript(Page, Page.GetType, Guid.NewGuid().ToString(), "alert('" + sMsg + "')", true);

}
bummi
  • 26,435
  • 13
  • 58
  • 97
1

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:

<script>
    var data = '<%= JsData %>';
    alert(data);
</script>

and to fill this data from the server side code-behind:

public partial class PageName : Page
{
    protected string JsData = "your message";

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.

Roland
  • 3,391
  • 5
  • 32
  • 63
1

Here's a method that I just wrote today, so that I can pass as many message boxes to the page as I want to:

/// <summary>
/// Shows a basic MessageBox on the passed in page
/// </summary>
/// <param name="page">The Page object to show the message on</param>
/// <param name="message">The message to show</param>
/// <returns></returns>
public static ShowMessageBox(Page page, string message)
{
    Type cstype = page.GetType();

    // Get a ClientScriptManager reference from the Page class.
    ClientScriptManager cs = page.ClientScript;

    // Find the first unregistered script number
    int ScriptNumber = 0;
    bool ScriptRegistered = false;
    do
    {
        ScriptNumber++;
        ScriptRegistered = cs.IsStartupScriptRegistered(cstype, "PopupScript" + ScriptNumber);
    } while (ScriptRegistered == true);

    //Execute the new script number that we found
    cs.RegisterStartupScript(cstype, "PopupScript" + ScriptNumber, "alert('" + message + "');", true);
}
1

There are a few solutions; if you are comfortable with CSS, here's a very flexible solution:

Create an appropriately styled Panel that resembles a "Message Box", put a Label in it and set its Visible property to false. Then whenever the user needs to see a message after a postback (e.g. pushing a button), from codebehind set the Labels Text property to the desired error message and set the Panel's Visible property to true.

Saeb Amini
  • 19,545
  • 8
  • 69
  • 71
0

You need to reference the namespace


using System.Windows.Form;

and then add in the code

protected void Button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show(" Hi....");

    }
Mamta D
  • 5,817
  • 3
  • 23
  • 40
-1

if you will include

System.Windows.forms

as namespace then it will conflict . Use

btn_click()
{

System.Windows.Forms.MessageBox.Show("Hello");

}
CRUSADER
  • 6,189
  • 3
  • 31
  • 60
-2

Right click the solution explorer and choose the add reference.one dialog box will be appear. On that select (.net)-> System.windows.form. Imports System.Windows.Forms (vb) and using System.windows.forms(C#) copy this in your coding and then write messagebox.show("").

NoNaMe
  • 5,410
  • 30
  • 73
  • 98
anu
  • 13
  • 1
-3

Just add the namespace:

System.Windows.forms 

to your web application reference or what ever, and you have the access to your:

MessageBox.Show("Here is my message");

I tried it and it worked.

Good luck.

mawburn
  • 2,048
  • 4
  • 27
  • 46