ASP.NET Web Application Message Box
Asked Answered
B

13

39

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?

Berti answered 15/3, 2012 at 12:55 Comment(0)
H
72

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

Hammerhead answered 15/3, 2012 at 12:59 Comment(5)
What is myStringVariable??Macias
myStringVariable is just a string. It would be set to the message you wish to display.Hammerhead
@Hammerhead 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?Alt
When I try this I just get No overload for method 'RegisterStartupScript' takes 4 argumentsShod
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 |.Tunnel
S
18

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");
Shutt answered 20/1, 2014 at 1:58 Comment(4)
I get "Extension Method must be static." Any idea?Megara
@usefulBee: You forgot to add static between public and void.Fiendish
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")Prosody
yeah but when you are working in own page class. Then you are not required to use this statementShutt
B
12

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.

Burial answered 23/7, 2014 at 15:55 Comment(2)
Getting Parser Error Message: Could not load type 'CSASPNETMessageBox.MessageBoxUserControl'.Suzerainty
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?Mohamedmohammad
V
3

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.

Vicennial answered 15/3, 2012 at 12:59 Comment(0)
F
2

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

Formation answered 15/3, 2012 at 13:0 Comment(0)
S
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.

Samoyed answered 15/3, 2012 at 13:11 Comment(0)
P
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);

}
Pawpaw answered 6/11, 2014 at 4:10 Comment(0)
F
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.

Flocculate answered 29/11, 2016 at 9:55 Comment(0)
P
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);
}
Pauly answered 11/6, 2020 at 15:43 Comment(0)
M
-1

if you will include

System.Windows.forms

as namespace then it will conflict . Use

btn_click()
{

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

}
Malvern answered 13/8, 2013 at 9:59 Comment(1)
No! This displays the message box on the server.Wreckful
V
-1

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....");

    }
Violetavioletta answered 20/11, 2014 at 4:53 Comment(2)
windows.Forms is not part of ASP.net. Completely different gameNarcho
+1, it's not the correct answer to the question but will help someone in the future with debugging on a local serverCutup
D
-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("").

Dhiren answered 31/12, 2012 at 5:33 Comment(1)
Richard is correct. Don't do this. This displays the message box on the server.Wreckful
C
-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.

Chronometer answered 9/8, 2013 at 20:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.