ASP.NET中MessageBox的实现

asp.net中没有MessageBox这个控件,固然可以插入Winform里的MessageBox,但一般不提倡,所以只能变通实现,主要有这几种方法:

1.直接利用javascript的alert和confirm函数:
在服务端的写法是:
1)alert
ScriptManager.RegisterStartupScript(this, typeof(Page), Guid.NewGuid().ToString(), "alert('Nothing changed.')", true);

 

2)confirm
将弹出窗口的onclick事件和confirm联系起来:
SaveButton.Attributes.Add("onclick", "return confirm('Are you sure you want to save it?');");

 

2.利用ajaxToolKit里的ModalPopupExtender和ConfirmButton两个控件:
1)ModalPopupExtender
在aspx文件里的写法:
< ajaxToolkit:ModalPopupExtender runat="server" ID="msgBox" TargetControlID="hiddenTargetControlForModalPopup"
PopupControlID="messageboxPanel" BackgroundCssClass="messagebox_parent" DropShadow="False"
RepositionMode="RepositionOnWindowResizeAndScroll" />
< asp:Button runat="server" ID="hiddenTargetControlForModalPopup" Style="display: none;" />
< asp:Panel runat="server" ID="messageboxPanel" Style="display:none; border: #003399 2px solid;  width: 400px; height: 125px;">< div style="text-align:center">Are you sure you want to save it?< /div >< div style="text-align:center" > < asp:Button id="okbutton" runat="server" onclick="okbutton_click" /> &nbsp;&nbsp;< asp:Button id="cancelbutton" runat="server" onclick="cancelbutton_click" />< /asp:Panel>
使用时,在服务端用msgBox.Show()方法来打开,用msgBox.Hide()方法关闭.

 

2)ConfirmButton
在aspx里:
< %@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
< ajaxToolkit:ConfirmButtonExtender Id="confirmBox" runat="server" ConfirmText="Are your sure you want to save it?" TargetControlID="saveButton" />
saveButton是保存按钮,当用户选择弹出窗口的OK键后就执行它的onclick事件里的语句.

ajaxToolKit本质上是用DIV来模拟弹出窗口.

 

3.自定义控件:
其实也是利用div来模拟,只不过做得复杂些.下面是一个实例:
ascx:
< %@ Control Language="C#" AutoEventWireup="true" CodeBehind="MessageBox.ascx.cs"
Inherits="Controls.MessageBox" %>
< %@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
< style type="text/css">
.messagebox_parent
{
color:Blue;
-moz-opacity:0.12;
background-color:#000;
filter:alpha(opacity=12);
opacity:0.12;
}
.messagebox_content
{
outline-style: none;
outline-style : invert;
outline-width: 0px;
border-bottom: #003399 2px solid;
text-align: center;
border: #003399 2px solid;
background: white;
cursor: auto;
display: block;
width: 400px;
height: 150px;
}
.messagebox_title
{
background: url(../../Images/vertgradient.gif) #003399 repeat-x 50% bottom;
font-size: 12px;
font-weight: bold;
text-decoration: none;
padding: 4px;
border-top: 0;
border-right: 0;
color: white;
vertical-align:baseline;
text-align: left;
cursor:pointer;
}
< /style>
< ajaxToolkit:ModalPopupExtender runat="server" ID="msgBox" TargetControlID="hiddenTargetControlForModalPopup"
PopupControlID="messageboxPanel" BackgroundCssClass="messagebox_parent" DropShadow="False"
RepositionMode="RepositionOnWindowResizeAndScroll">
< /ajaxToolkit:ModalPopupExtender>
< asp:Button runat="server" ID="hiddenTargetControlForModalPopup" Style="display: none;" />
< asp:Panel runat="server" ID="messageboxPanel" CssClass="messagebox_content" Style="display:none; ">
< asp:Panel runat="Server" ID="messageBoxTitleHandle" CssClass="messagebox_title">
< div id="MessageBoxCaption" runat="server">
< /div>
< /asp:Panel>
< div style="float: left; margin-left: 10px; margin-top: 10px;">
< asp:Image ID="messageBoxIcon" runat="server" ImageUrl="../Images/exclamation.gif" style="width: 64px; height: 64px;" />
< /div>
< div style="display:table;height:80px;position:relative;overflow:hidden; text-align:left; padding-left:10px; padding-right: 10px;">
< div style="display:table-cell;vertical-align:middle;position:absolute;top:50%;">
< div id="MessageBoxText" runat="server" style="position:relative;top:-50%;">
< /div>
< /div>
< /div>
< div>
< asp:Button runat="server" ID="button1" Text="button1" style="width:70px; margin:5px;" onclick="Button_Click" />
< asp:Button runat="server" ID="button2" Text="button2" style="width:70px; margin:5px;" onclick="Button_Click" />
< asp:Button runat="server" ID="button3" Text="button3" style="width:70px; margin:5px;" onclick="Button_Click" />
< /div>
< /asp:Panel>
 
ascx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
namespace Controls
{
public partial class MessageBox : System.Web.UI.UserControl
{
public event EventHandler<MessageBoxArgs> MessageBoxButtonClick;
protected void Page_Load(object sender, EventArgs e)
{
}
private void SetButton(Button button, DialogResult dialogResult)
{
button.Text = dialogResult.ToString();
button.Attributes["DialogResult"] = ((byte)dialogResult).ToString();
if (dialogResult == DialogResult.None)
{
button.Style["display"] = "none";
}
else
{
button.Style["display"] = "inline";
}
}
public void Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon)
{
switch (buttons)
{
case MessageBoxButtons.AbortRetryIgnore:
SetButton(button1, DialogResult.Abort);
SetButton(button2, DialogResult.Retry);
SetButton(button3, DialogResult.Ignore);
break;
case MessageBoxButtons.OK:
SetButton(button1, DialogResult.OK);
SetButton(button2, DialogResult.None);
SetButton(button3, DialogResult.None);
break;
case MessageBoxButtons.OKCancel:
SetButton(button1, DialogResult.OK);
SetButton(button2, DialogResult.Cancel);
SetButton(button3, DialogResult.None);
break;
case MessageBoxButtons.RetryCancel:
SetButton(button1, DialogResult.Retry);
SetButton(button2, DialogResult.Cancel);
SetButton(button3, DialogResult.None);
break;
case MessageBoxButtons.YesNo:
SetButton(button1, DialogResult.Yes);
SetButton(button2, DialogResult.No);
SetButton(button3, DialogResult.None);
break;
case MessageBoxButtons.YesNoCancel:
SetButton(button1, DialogResult.Yes);
SetButton(button2, DialogResult.No);
SetButton(button3, DialogResult.Cancel);
break;
}
switch (icon)
{
case MessageBoxIcon.Error:
messageBoxIcon.ImageUrl = "../Images/error.gif";
break;
case MessageBoxIcon.Information:
messageBoxIcon.ImageUrl = "~/Images/info.gif";
break;
case MessageBoxIcon.Exclamation:
messageBoxIcon.ImageUrl = "../Images/exclamation.gif";
break;
}
MessageBoxCaption.InnerText = caption;
MessageBoxText.InnerText = text;
msgBox.Show();
}
public void Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, string refNo)
{
messageboxPanel.Attributes["RefNo"] = refNo;
Show(text, caption, buttons, icon);
}
public void Hide()
{
msgBox.Hide();
}
protected void Button_Click(object sender, EventArgs e)
{
if (MessageBoxButtonClick != null)
{
Button button = sender as Button;
if (button != null)
{
DialogResult dialogResult = (DialogResult)(Convert.ToByte(button.Attributes["DialogResult"]));
string refNo = messageboxPanel.Attributes["RefNo"];
MessageBoxArgs args = new MessageBoxArgs(dialogResult, refNo);
MessageBoxButtonClick(this, args);
}
}
}
}
public class MessageBoxArgs : EventArgs
{
private DialogResult _dialogResult;
private string _refNo = string.Empty;
public DialogResult DialogResult
{
get { return _dialogResult; }
}
public string RefNo
{
get { return _refNo; }
}
public MessageBoxArgs(DialogResult dialogResult)
{
_dialogResult = dialogResult;
}
public MessageBoxArgs(DialogResult dialogResult, string refNo)
{
_dialogResult = dialogResult;
_refNo = refNo;
}
}
[Flags]
public enum MessageBoxButtons
{
OK,
OKCancel,
AbortRetryIgnore,
YesNoCancel,
YesNo,
RetryCancel
}
[Flags]
public enum MessageBoxIcon
{
None,
Hand,
Question,
Exclamation,
Asterisk,
Stop,
Error,
Warning,
Information
}
[Flags]
public enum DialogResult
{
None,
OK,
Cancel,
Abort,
Retry,
Ignore,
Yes,
No
}
}
使用时,在aspx文件里:
< %@ Register src="MessageBox.ascx" tagname="MessageBox" tagprefix="uc1" %>
< asp:UpdatePanel ID="UpdatePanel5" runat="server">
< ContentTemplate>
< uc1:MessageBox ID="confirmMsgBox" runat="server" />
< /ContentTemplate>
< /asp:UpdatePanel>
在aspx.cs文件里:
protected void Page_Load(object sender, EventArgs e)
{
   confirmMsgBox.MessageBoxButtonClick += onOKClicked;
   confirmMsgBox.MessageBoxButtonClick += onCancelClicked;
}
//打开messageBox的代码:
confirmMsgBox.Show("Are you sure you want to save it?", "Confirm", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
//处理按钮事件的代码:
private void onOKClicked(object sender, MessageBoxArgs arg)
{
if (arg.RefNo == "save" && are.DialogResult == DialogResult.OK)
{
   //其他代码
}
}
}
private void onCancelClicked(object sender, MessageBoxArgs arg)
{
if (arg.RefNo == "save" && are.DialogResult == DialogResult.Cancel)
{
   //其他代码
}
}
}
RefNo属性是为了实现MessageBox的共享,用来区别不同的调用对象.

这个方法的显示效果比较好,共享也比较方便.这是它的优点.缺点是当在一个ModalPopupExtender上使用时,在关闭messageBox的同时也会把后面那个ModalPopupExtender关闭.如果messageBox里一个按钮点击后需要保持后面的那个ModalPopupExtender显示, 另一个按钮点击后关闭后面的那个ModalPopupExtender,可以在前一个按钮的OnClientClick事件里加上:return hideMessageBox('confirmMsgBox');
 hideMessageBox函数的代码如下:
function hideMessageBox(controlName) {
var ids = document.getElementsByTagName('INPUT');
for (var i = 0; i < ids.length; i++) {
if (ids[i].id.match(controlName) != null) {
ids[i].style.display = 'none';
}
}
ids = document.getElementsByTagName('DIV');
for (var i = 0; i < ids.length; i++) {
if (ids[i].id.match(controlName) != null) {
ids[i].style.display = 'none';
}
}
ids = document.getElementsByTagName('IMG');
for (var i = 0; i < ids.length; i++) {
if (ids[i].id.match(controlName) != null) {
ids[i].style.display = 'none';
}
}
return false;
}
 但是如果不管点击messageBox里的哪个按钮都想保持后面的ModalPopupExtender显示,这个方法就不行了.

 

4.用模态窗口模拟messageBox:
客户端:(假设使用了master page)
function openMessageWindow(message, type) {
if (message != null && message != '') {
var messageType = document.getElementByID('< %= messageType.ClientID %>');
messageType.value = type;
var dialogResult = window.showModalDialog('messageBoxWindow.aspx?message=' + message, 'Confirm', 'dialogWidth:410px;dialogHeight:182px;center:yes;status:no;resizable:no');
if (dialogResult == "yes") {
var yesButton = document.getElementById('< %= yesButton.ClientID %>');
yesButton.click();
}
else if (dialogResult == "no") {
var noButton = document.getElementById('< %= noButton.ClientID %>');
noButton.click();
}
}
}
 
< asp:Button ID="yesButton" runat="server" style="display:none"
onclick="yesButton_Click" />
< asp:Button id="noButton" runat="server"
style="display:none" onclick="noButton_Click" />
 < asp:HiddenField id="messageType" runat="server" />

服务端的调用代码:
ScriptManager.RegisterStartupScript(this.Page, typeof(Page), Guid.NewGuid().ToString(), "openMessageWindow('Are you sure you want to save it?','save');", true);
return;
}

处理按钮事件的代码:
protected void yesButton_Click(object sender, EventArgs e)
{
  if (messageType.Value == "save")
  {
      //执行保存数据的操作
  }
}
 
messageBoxWindow.aspx文件的内容:
< %@ Page Language="C#" AutoEventWireup="true" CodeBehind="MessageBoxWindow.aspx.cs" Inherits="WebForm.MessageBoxWindow" %>
< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
< html xmlns="http://www.w3.org/1999/xhtml" >
< head runat="server">
< title>Confirm</title>
< link href="Content/Style.css" rel="stylesheet" type="text/css" />
< script type="text/javascript">
function setReturnValue(returnString) {
window.returnValue = returnString;
window.close();
}
< /script>
< /head>
< body>
< form id="form1" runat="server">
< div style="text-align:center; margin-top:60px">
< div style="margin-bottom:30px">
< asp:Label ID="messageLabel" runat="server" />
< /div>
< div>
< input type="button" class="button" onclick="setReturnValue('yes')" value="Yes" />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="button" class="button" onclick="setReturnValue('no')" value="No" />
< /div>
< /div>
< /form>
< /body>
< /html>

messageBoxWindow.aspx.cs文件的内容:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebForm
{
public partial class MessageBoxWindow : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
messageLabel.Text = Request.QueryString["message"];
}
}
}
messageType这个HiddenField的作用是实现这个模拟的messageBox能被多个对象共享,用它的值来区分调用对象.

--------------------- 本文来自 使我做你和平之子 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/hzzasdf/article/details/4701724?utm_source=copy 

posted on 2018-10-08 22:11  asdyzh  阅读(1617)  评论(0编辑  收藏  举报

导航