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; background-color:white; 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" οnclick="okbutton_click" /> &nbsp;&nbsp;< asp:Button id="cancelbutton" runat="server" οnclick="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;" οnclick="Button_Click" />
< asp:Button runat="server" ID="button2" Text="button2" style="width:70px; margin:5px;" οnclick="Button_Click" />
< asp:Button runat="server" ID="button3" Text="button3" style="width:70px; margin:5px;" οnclick="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"
οnclick="yesButton_Click" />
< asp:Button id="noButton" runat="server"
style="display:none" οnclick="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" οnclick="setReturnValue('yes')" value="Yes" />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="button" class="button" οnclick="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能被多个对象共享,用它的值来区分调用对象.

 

小结:

以上方法,1最简单,但是受javascript的局限,界面美观性较差,更重要的是无法实现多于两个按钮的messageBox,按钮的事件只能在客户端处理. 方法2的界面较美观,使用也比较简便.方法3的界面完全由用户定制,功能比较强大,界面也很美观,调用稍微复杂些. 这两种方法的主要缺点是在ModalPopupExtender上使用不便. 方法4受浏览器窗口的限制,界面的美观性不如方法2,3,但是比方法1要好.克服了方法2,3的缺点.主要不足是性能不如方法2,3.

评论 1 您还未登录,请先 登录 后发表或查看评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页

打赏作者

使我做你和平之子

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值