[c#] 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?

This question is related to c# asp.net web-applications code-behind messagebox

The answer is


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


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

}

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

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


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.


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.


if you will include

System.Windows.forms

as namespace then it will conflict . Use

btn_click()
{

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

}

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


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.


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


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.


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

    }

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

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to web-applications

Spring - No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call How do I choose the URL for my Spring Boot webapp? Difference between MEAN.js and MEAN.io External VS2013 build error "error MSB4019: The imported project <path> was not found" How to unpackage and repackage a WAR file IntelliJ, can't start simple web application: Unable to ping server at localhost:1099 Using form input to access camera and immediately upload photos using web app Pass user defined environment variable to tomcat ASP.NET: HTTP Error 500.19 – Internal Server Error 0x8007000d Best practices when running Node.js with port 80 (Ubuntu / Linode)

Examples related to code-behind

How to call a C# function from JavaScript? how to access master page control from content page Set Text property of asp:label in Javascript PROPER way ASP.NET Web Application Message Box How to programmatically set the Image source Accessing a resource via codebehind in WPF Adding css class through aspx code behind Passing arguments to JavaScript function from code-behind The name 'controlname' does not exist in the current context ASP.net page without a code behind

Examples related to messagebox

HTML - Alert Box when loading page Close a MessageBox after several seconds How to pop an alert message box using PHP? C# MessageBox dialog result VBA code to show Message Box popup if the formula in the target cell exceeds a certain value ASP.NET Web Application Message Box How to get text and a variable in a messagebox How to add message box with 'OK' button? How to get DataGridView cell value in messagebox? MessageBox Buttons?