ASP.NET Web应用程序消息框

39
在一个asp.net的Windows窗体应用程序中,你可以在C#代码后台使用:
MessageBox.Show("Here is my message");

在asp.net Web应用程序中是否有相当于此功能的东西?我可以从C#代码后台调用某些内容以向用户显示消息框吗?

此功能的示例用法:我有一个按钮,在代码后台中加载文件。当文件被加载或出现错误时,我想弹出一个消息框向用户显示结果。

对此有什么想法吗?

13个回答

72

你想使用一个警告框,不幸的是它不像windows forms那样好看。

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

类似于这个问题:http://forums.asp.net/t/1461308.aspx/1

(注:该链接为英文网页,需要自行翻译)


1
我的字符串变量是什么? - who-aditya-nawandar
3
myStringVariable只是一个字符串,它将被设置为您希望显示的消息。 - Gage
@Gage 当事件被触发后,消息框打开时,用户会看到一个“确定”按钮。有没有办法将Response.Redirect("desired/path.aspx");与此连接起来? - JsonStatham
当我尝试这样做时,我只收到“没有重载方法'RegisterStartupScript'接受4个参数”的错误信息。 - Bassie
如果您想使用网页中的多个消息,您应该给它们不同的名称,例如myalert1,myalert2等。如果您的消息包含单引号',它将无法正常工作,您必须将其替换为其他字符,例如|。 - Sergio Prats

17

或者在您的解决方案中创建像这样的方法:

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

然后你可以这样使用:

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

我收到了“扩展方法必须是静态的”这个错误信息。你有什么想法吗? - usefulBee
1
@usefulBee:你忘记在publicvoid之间加上static了。 - Heinzi
1
该类创建了一个扩展方法来扩展Page对象。您可以使用页面实例调用它:this.Show("这是我的消息") 或者将页面作为参数提供:MessageBox.Show(this, "这是我的消息")。 - flodis
是的,但当您在自己的页面类中工作时,则无需使用此语句。 - Ali Humayun

12

我认为微软提供的这个链接是在ASP.NET中展示消息框的最佳方式。

此外,它还提供了像“是”和“否”这样的选项。

如何在你的项目中使用链接中的类的说明:

  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.


获取解析器错误消息:无法加载类型“CSASPNETMessageBox.MessageBoxUserControl”。 - mappingman
1
这个解决方案似乎非常适合我的问题...直到我点击链接发现它们不再起作用(感谢微软!)。有人可以在第3步和第4步中发布MessageBox.cs和MessageBoxCore.cs的代码吗?或者给我一个提示,那段代码应该是什么样子的? - samp

3
并不是。服务器端的代码是在服务器上执行的。你可以使用JavaScript在客户端显示一些内容,但它只会在客户端执行。这就是客户端服务器Web技术的本质。
当你收到响应时,你基本上与服务器断开连接。

2

为什么不能使用jQuery弹出框来实现这个目的?我建议使用bpopup来实现。了解更多信息,请访问:http://dinbror.dk/bpopup/


1
正如其他人指出的那样,消息框将是客户端Javascript。因此问题在于如何从服务器端强制使用客户端JS消息框。一个简单的解决方案是在HTML中包含这个:
<script>
    var data = '<%= JsData %>';
    alert(data);
</script>

并从服务器端代码后台填充此数据

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

请注意,字符串值应该是一个Javascript字符串,即一行代码,但它可能包含转义的换行符作为\n
现在你可以使用所有的Javascript或JQuery技巧,在客户端上对消息文本进行任何你想要的操作,比如显示一个简单的alert(),如上面的代码示例所示,或者复杂的消息框或消息横幅。
(注意,弹出窗口有时会被反感和阻止)
还要注意的是,由于HTTP协议的原因,只有当用户向服务器发送HTTP请求时,消息才能被显示。与WinForm应用程序不同,Web服务器不能随意向客户端推送消息。
如果你想只显示一次消息,而不是在用户按F5刷新页面后再次显示,你可以使用javascript代码设置和读取cookie。无论如何,这种方法的好处是它是从服务器到客户端的javascript获取数据的一种简单方式,并且你可以使用所有javascript功能来实现任何你喜欢的东西。

1

有几种解决方案;如果您熟悉 CSS,这是一个非常灵活的解决方案:

创建一个外观类似于“消息框”的适当样式的 Panel,在其中放置一个 Label 并将其 Visible 属性设置为 false。然后,每当用户需要在 postback 后(例如按下按钮)查看消息时,从 codebehind 将 LabelText 属性设置为所需的错误消息,并将 PanelVisible 属性设置为 true


1
'ASP.net消息框'
'向ASP.Net页面添加ScriptManager'
<asp:scriptmanager id="ScriptManager1" runat="server" />

尝试:
{

  string sMsg = "My Message";

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

}

1

这是我今天刚写的一个方法,可以在页面上传递尽可能多的消息框:

/// <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

如果你包含

System.Windows.forms

如果使用命名空间,可能会发生冲突。

btn_click()
{

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

}

8
不!这会在服务器上显示消息框。 - Krisztián Balla

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接