Immediately redirect to another page in WPF - c#

I have a page that several other pages navigate to. However in some circumstances the user should not see this page, so I want to send them to another page instead.
Rather than update the rest of the calling code, I just want to change this page to handle it.
public MyPage()
{
Loaded += MyPage_Loaded;
InitializeComponent();
// Other stuff
}
void MyPage_Loaded(object sender, RoutedEventArgs e)
{
if(condition)
NavigationService.Navigate(someUri);
}
Since the NavigationService isn't available in the constructor I have to hook up to the Loaded event and do the redirect there. The problem is that the page has already been loaded and displayed to the user. There is also a slight delay before redirecting the user.
Is there a better way to do this where the redirect is seamless?

Related

How to notify the page when GoBack() happened?

Here is what my app does:
The first page can navigate to the second page, and the second page displays a list of data. The user can choose one of them then the app will bring the data back to the first page.
Sounds easy, but I'm confused with the Windows Mobile Navigation Model.
The first page navigates to the second page, using this code:
this.Frame.Navigate(typeof(SecondPage));
and the second page uses the code below to go back:
this.Frame.GoBack();
How could the first page know if the second page disappeared? I want to update the UI on the first page after the second page disappeared.
Now, I used a static class to keep the data that user picks, but I have no idea when should be the right time to update the first page.
Is there any way to get an event or notification?
This is quite simple, since UWP does this for you. I noticed you're not using MVVM, so you can simply override the OnNavigatedTo event in your page. This event is triggered when navigation to your page is completed (and thus the second screen dissapeared). Simply check for NavigationMode.Back to confirm you're returning and not navigating forward.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
if (e.NavigationMode == NavigationMode.Back)
{
// coming from 2nd page, so refresh your data
}
}

How to re-use already bound data in a user control on post back

I have a user control that I dynamically add to a Panel. I also have a couple of other functionality in the aspx page like search which is inside an update panel that causes the page to post back. From what I have read so far is that dynamic control needs to be bound on each page load. This works fine but the issue is that the user control takes a bit of time (like 3s) and thus all request operations takes longer because the user control is being bound every time.
If I load the user control inside the Page.IsPostBack condition and load it only on page load then user control is visible on post back but all the associated events in the user control is not fires.
So, Is there a way in which I can store the user control data in a session and then bind it if I know that the data is not going to change and hence reducing the 3s delay to load the user control.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadUserControl(); // Only loaded on page load.Faster, but user control
//functionalities break on post back. Maybe
// because it is not loaded again.
}
//LoadUserControl(); // User control loads fine. But even a totally unrelated
// post back causes the already loaded User Control to load
// again. 3s delay :(
}
The method used to load the user control is
private void LoadUserControl()
{
var control = LoadControl("A Dynamic ascx page");
control.ID = "contentControl";
panel1.Controls.Clear(); //panel1 is the placeholder in aspx page
panel1.Controls.Add(control);
Session["LoadedControls"] = control;
}
So I tried to save the loaded control in session and add in to the placeholder panel as such
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadUserControl(); // Only loaded on page load.Faster, but user control
//functionalities break on post back. Maybe
// because it is not loaded again.
}
if ((Control)Session["LoadedControls"] != null)
{
panel1.Controls.Clear();
panel1.Controls.Add((Control)Session["LoadedControls"]);
}
}
this does not work as expected either. I do not get any of the data present in the user control.
The user control has 2 RadGrid and 2 RadHTMLChart. I did not want to add it since this is already a huge post. the data for the controls in user controls is also being stored in session for binding again. But I am unable to find a way to add the user control dynamically with the bound data.

How to make a Windows Runtime Page refresh when it goes to foreground?

I want to make a Windows Runtime Page refresh/reload every time it goes to foreground. I have tried to add a handler to the Loaded event, but the Loaded event is only fired when the page is first loaded, which unlike the DOMContentLoaded event of HTML. What is the proper way to do so?
Thanks.
public sealed partial class MainPage : Page {
public MainPage() {
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Disabled;
this.Loaded += (s, e) => {
Debug.WriteLine("Loaded at " + DateTime.Now.ToString());
// Code that should be executed when the page goes to the foreground each time
};
}
}
The OnNavigatedTo method (as documented on the MSDN page you've put in your question) will be called every time a Page is navigated to.
You can use the NavigationEventArgs to determine what kind of navigation took place and handle this appropriately. In your case you would add code to refresh your page's content.
As Romasz points out, this will not help you in WinRT XAML stack when your app is resumed as the page doesn't get a call to OnNavigatedTo in that case.
For that you'd have to detect the application resume in your app and send a message to your page (or it's data source/View Model) to refresh.
Be aware of the app resume/suspend guidelines however (see MSDN).

WebBrowser does not change

I'm making an application in C# which, depending of a variable, shows one web page or another.
When I push a button, the program load the userName and the webBrowser should show a different web page. Here is my source code:
private void button1_Click(object sender, EventArgs e) {
string url = "http://www.url.com/" + userName;
webBrowser1.Navigate(url);
webBrowser1.Refresh();
}
The problem is that, when I push the button a second time with a different variable, the web browser reloads the same web page.
I think it's because of the webBrowser1.Refresh(); you don't need it and i think you are pushing the button 2 consecutive times with different values and it gives you the impression that it's loading another page but it isn't. try to remove that line and add an event to the Navigated method of your WebBrowser object in order to obtain a feedback when the browser is done loading the page.
I have solved my problem. I had set the property AllowNavigation to false, so, when I tried to change the web page, it didn't allow me to did it. Anyway, I needed to remove the Refreshcall to make it work.

Calling a function before Page_Load

I have a button that calls function A()
When I click on it I want the calls to be made in that order:
A()
Page_Load()
Right now it's doing:
Page_Load()
A()
Is there a way around that or is it just by design and there's nothing I can do about it?
The easiest way to do this would be to use a HTML Submit button and check to see if it is in the Form on every postback in Page_Init
public void Page_Init(object o, EventArgs e)
{
if(!string.IsNullOrEmpty(Request.Form["MyButtonName"]))
{
A();
}
}
And in your ASP.NET code:
<Button Type="Submit" Name="MyButtonName" Value="Press Here To Do Stuff Early!" />
I think that will work.
Control events (such as the click events of buttons) are called after page_load. The controls are not guarenteed to be fully initialized prior to page_load. If you really need to call a function before page_load has been called based on whether a button has been pressed you'll have to examine the request to check if the button has been pressed (basically old school ASP)
You need to call your function in the Page_Init. Page_Init will happen before Page_Load.
Here's an Overview of the ASP.NET Page Lifecycle.
Not exactly: ASP.NET will always call Page_Load before handling postback events like Button_Click.
However, you can accomplish what you want by redirecting to your page after handling the postback event. (Using the Post-Redirect-Get pattern.)
Inside your Page_Load method, you can avoid running any relevant code twice by checking to see if it's a postback first:
if (!this.IsPostBack) {
// Do something resource-intensive that you only want to do on GETs
}
As Jeff Sternal answered, The Post-Redirect-Get pattern is a good way of solving a problem like this.
In my circumstances i had a calendar and if you clicked a date it would add that to a scheduler. The scheduler would have buttons on each new date that needed to have onclick functions tied to them.
Because the new row was being added with a linkbutton(on the calendar), in the code the new scheduler date was being added at the Postback event handling meaning that the new set of buttons wouldn't have a command tied to them.
The page life Cycle
Post Get Redirect
I don't think it's possible, at least, not in the way described by your question. When you click a button it will send a request to the server which in turn will start processing it, and follow the ASP.NET Page Lifecycle as posted by Joseph.
Alternatively you could try making an AJAX call to a page without reloading the current one you're on and do whatever processing you require.
This is what you want to do for Page Init is called before Page Load.
Take a look at the ASP.net Page Life Cycle
public void Page_Init(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//CALL YOU FUNCTION A()
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
}
If your actual goal here is to have your "page loading code" happen after your event handler runs -- for example, if clicking your button changes something in your database, and you want the updated data to be reflected on the page when it loads -- then you could have your "page loading code" get called from a method that gets called later in the ASP.NET page life cycle than your event handler, such as Page_PreRender, instead of calling it from Page_Load.
For example, here's a simplified excerpt from an .aspx.cs page class that has a button event handler that runs before the page population logic, and a confirmation message that is visible on the page only after the button was clicked:
// Runs *before* the button event handler
protected void Page_Load() {
_myConfirmationMessage.Visible = false;
}
// Runs *after* the button event handler
protected void Page_PreRender() {
// (...Code to populate page controls with database data goes here...)
}
// Event handler for an asp:Button on the page
protected void myButton_Click(object sender, EventArgs e) {
// (...Code to update database data goes here...)
_myConfirmationMessage.Visible = true;
}

Categories

Resources