Reputation: 1425
I'm fairly new to ASP.Net but have used ASP Classic before.
I'm trying to figure out how to return a status message to my front-end page from a "code behind" page.
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!";
}
}
When my page posts to itself I'm not able to see the msg I'm expecting in the status label of my front-end page.
I'm guessing this is because the Page_Load function is executing before my action is performed or something like that.
I hope it's clear what I'm trying to achieve, can anyone point me in the right direction?
Upvotes: 1
Views: 1694
Reputation: 1
protected void action(object sender, EventArgs e)
{
Response.Write("<script type=\"text/javascript\">alert('Your Message');</script>");
}
Upvotes: 0
Reputation: 3720
You could achieve this using Session assuming you have button or any other other control that causes postback and that triggers action function.
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;
}
}
Upvotes: 0
Reputation: 1762
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!";
}
Upvotes: 2
Reputation: 10191
Set your text on OnPreRender instead of OnLoad. It fires after the event and should be used to do as much UI as possible.
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!";
}
}
Typically if you're running through a few events this is the best way to do it - you don't know which order the events will fire in so you want your message to be set at the end. However unless you need to do anything more complex why not just set it in the event itself and get rid of the private variable and extra method call?
public partial class test: System.Web.UI.Page
{
protected void action(object sender, EventArgs e)
{
status.Text = "Hello world!";
}
}
Upvotes: 2