简体   繁体   中英

ASP.NET Web Application Message Box

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?

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

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

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.

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.

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?

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

'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);

}

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, ie 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.

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);
}

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 (eg pushing a button), from codebehind set the Label s Text property to the desired error message and set the Panel 's Visible property to true .

if you will include

System.Windows.forms

as namespace then it will conflict . Use

btn_click()
{

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

}

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

    }

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM