在ASP.NET中自定义MessageBox.Show()
本文关键字:Show MessageBox 自定义 ASP NET | 更新日期: 2023-09-27 18:03:37
我想重建"look &WinForms应用程序的MessageBox.Show()
带"look &我的意思是用我已经实现的ShowMessage方法的逻辑调用MessageBox.Show()命令
我当前的代码落后:
public partial class Testpage : System.Web.UI.Page
{
public enum MessageBoxIcon { Information, Error, Warning }
protected void Page_Load(object sender, EventArgs e)
{
ShowMessage("Testmessage", MessageBoxIcon.Error, ex);
}
private void ShowMessage(string title, string message, MessageBoxIcon type, Exception ex)
{
if (type == MessageBoxIcon.Information)
{
pnlMsgBox.CssClass = "MessageBoxInformation";
imgMsgBox.ImageUrl = "Resources/img/icon/MessageBoxIcon.Information.png";
}
else if (type == MessageBoxIcon.Warning)
{
pnlMsgBox.CssClass = "MessageBoxWarning";
imgMsgBox.ImageUrl = "Resources/img/icon/MessageBoxIcon.Warning.png";
}
else if (type == MessageBoxIcon.Error)
{
pnlMsgBox.CssClass = "MessageBoxError";
imgMsgBox.ImageUrl = "Resources/img/icon/MessageBoxIcon.Error.png";
}
else
throw new NotImplementedException();
lblMsgBox.Text = "<span style='"font-size: large;'">" + title + "</span><br /><br />" + message;
#if (DEBUG)
if (ex != null)
lblMsgBox.Text += "<br /><br /><b>Debug information:</b> " + ex.Message;
#endif
pnlMsgBox.Visible = true;
updPnl.Update();
}
}
我想这样命名:
protected void Page_Load(object sender, EventArgs e)
{
MessageBox.Show("Testmessage", MessageBoxIcon.Error, ex);
}
,
public static class MessageBox : Testpage
{
public static void Show(string message)
{
// do stuff with the page controls.
}
}
不起作用,因为Testpage不是静态的。
有谁能给我一些建议吗?看了对上一个答案的评论,我想下一个:
很难从分离的静态类访问当前页面上下文。那么,我建议做下一步:
定义下一个接口:public interface IMessageBoxContainer
{
UpdatePanel UpdatePanel { get; }
Label Label { get; }
}
并在您的页面中实现它:
public partial class _Default : System.Web.UI.Page, IMessageBoxContainer
{
protected void Page_Load(object sender, EventArgs e)
{
}
public UpdatePanel UpdatePanel
{
get { return updatePanel1; }
}
public Label Label
{
get { return label1; }
}
}
这些步骤使您可以从任何地方访问您的页面。之后实现你的MessageBox非静态类:
public class MessageBox
{
private IMessageBoxContainer container = null;
public MessageBox(IMessageBoxContainer _container)
{
container = _container;
}
public void Show(string message)
{
container.Label.Text = message;
container.UpdatePanel.Update();
}
}
为什么非静态?因为如果你做容器字段为静态并设置他的值在页面的任何地方(例如在Page_Load),当另一个页面将加载-你的容器属性将重置。但是,如果没有这个指向当前页面的指针字段,您就无法访问指定的控件。
之后,你可以这样使用你的类:
protected void Button1_Click(object sender, EventArgs e)
{
var box = new MessageBox(this);
box.ShowMessage("hello world");
}
所以,你得到了你的MessageBox的分离实现逻辑和简单地使用它,对吗?但不幸的是,它不是静态的
试试:
public static class MessageBox
{
public static void Show(string message)
{
HttpContext.Current.Response.Write(string.Format("<script>alert('{0}');</script>", message));
}
}
当然,你需要自己实现正确的JavaScript来在客户端显示你的MessageBox。但我认为你的做法是错误的。对于你的方法编程尝试看在ASP。asp.net MVC,因为经典的ASP。. NET不完全支持JavaScript编码。