在ASP.NET中发布后返回状态消息到页面
本文关键字:消息 状态 返回 NET ASP | 更新日期: 2023-09-27 18:17:29
我对ASP相当陌生。. Net,但是以前用过ASP Classic。
我正试图找出如何从"代码后面"页面返回状态消息到我的前端页面。
public partial class test: System.Web.UI.Page
{
private String msg;
protected void Page_Load(object sender, EventArgs e)
{
status.Text = msg;
}
protected void action(object sender, EventArgs e)
{
msg = "Hello world!";
}
}
当我的页面向自己发布时,我无法在前端页面的状态标签中看到我期望的消息
我猜这是因为Page_Load函数在我的操作执行之前执行或类似的东西。
我希望你清楚我想要达到的目标,谁能给我指出正确的方向?
将文本设置为OnPreRender而不是OnLoad。它在事件发生后触发,应该用来做尽可能多的UI。
public partial class test: System.Web.UI.Page
{
private String msg;
protected void OnPreRender(object sender, EventArgs e)
{
status.Text = msg;
}
protected void action(object sender, EventArgs e)
{
msg = "Hello world!";
}
}
通常情况下,如果您正在运行几个事件,这是最好的方法-您不知道事件将以哪种顺序触发,因此您希望在最后设置消息。然而,除非你需要做任何更复杂的事情,为什么不把它设置在事件本身,摆脱私有变量和额外的方法调用?
public partial class test: System.Web.UI.Page
{
protected void action(object sender, EventArgs e)
{
status.Text = "Hello world!";
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!isPostBack)
{
status.Text = "First time on page";
}
}
protected void action(object sender, EventArgs e)
{
status.Text = "Hello world!";
}
您可以使用Session实现这一点,假设您有按钮或任何其他控件,导致回发,并触发动作功能。
public partial class test: System.Web.UI.Page
{
private String msg;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostback)
{
Session["Message"] = null;
}
else
{
status.Text = Session["message"].ToString();
}
}
protected void action(object sender, EventArgs e)
{
msg = "Hello world!";
Session["message"] = msg;
}
}
protected void action(object sender, EventArgs e)
{
Response.Write("<script type='"text/javascript'">alert('Your Message');</script>");
}