我是 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!";
}
}
通常,如果您正在运行几个事件,这是最好的方法 - 您不知道事件将按哪个顺序触发,因此您希望在最后设置消息。但是,除非您需要做任何更复杂的事情,否则为什么不直接在事件本身中设置它并摆脱私有(private)变量和额外的方法调用呢?
public partial class test: System.Web.UI.Page
{
protected void action(object sender, EventArgs e)
{
status.Text = "Hello world!";
}
}
