ASP.NET Previous Page - asp.net

I have page and I am displaying the same page for n number of times and binding Various Data.
There is a back button on the page, When I click on it it should just take the page where it should diplay the previous data in the controls.
I tried Server.Transfer, Response.Redirect(), But they are taking to the page I wanted but not to the immediate previous page.
Please help.
Thank you
Hari Gillala

May be this helps;
protected void Page_Load(object sender, EventArgs e)
{
this.btnBack.OnClientClick = "javascript:window.history.go(-1);return false;";
}

Would doing it on the client side suffice? Just use history.go(-1) on click of the button.

Server side:
You can store the data which has to be bound to the controls in the session.Create session variables before rendering the pages, give different names to the session variable, may be you can use static variable for naming..

Why don't you utilize History object of JavaScript?
http://www.javascriptkit.com/jsref/history.shtml
http://www.defaultdotaspx.com/Answer.aspx?QuestionType=JavaScript&QuestionID=264
http://www.developertutorials.com/questions/question/q-147.php
Are you binding "various data" via AJAX?
Hope this helps!

I'm guessing that what you mean in your question is: I have a bunch of filters on my page and every time a filter gets changed I want to create a new item in the browser history so I can use the Back button to go back through my filters.
Have a look at the AddHistoryPoint method (+ overloads) of the ScriptManager object. This method allows you to save the state of your controls into a collection and save that into a URL that gets inserted into your browser's history collection, so that you can then retrieve it when the Back button is pressed and reload the state into the controls on your page.

Related

ASP.NET conditional yes/no messagebox

I have an asp:Button that fires a code behind function on the OnClick event. In that OnClick event several things happen, and among those things I do a check in the database for if I need to ask the user a yes or no question. For that I need a message box. First I did it like this:
protected void MyButton_Onclick(object sender, EventArgs e)
{
// lots of stuff happening
bool iNeedToAskTheUser = INeedToAskTheUser(stuff);
if (iNeedToAskTheUser)
{
DialogResult result = MessageBox.Show("Do you want to fix all objects?", "Fix objects", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes) // do stuff
}
// some other stuff
}
This works fine locally but not when deployed, so I figure I would need to use ScriptManager.RegisterStartupScript instead. I could just add javascript on the ASPX page that fires up a dialog and saves the response in a hidden control that I can then look at, but I don't want to fire up the dialog unless I have to, which I check for before I do the DialogResult in the code above. So I can't do that immediately when the user clicks the button.
Is there any way I can use ScriptManager.RegisterStartupScript in "the middle" of my _OnClick code so that I can choose whether or not to actually show the button, and then also know if the user clicked yes or no, (preferably) without doing a postback?
I've been thinking and testing two different solutions:
Use ScriptManager.RegisterStartupScript in code behind to fire a JavaScript confirm function on the ASPX page. The JavaScript function would set a value in a hidden control depending on if the user answered yes or no and then my code behind stuff would check the value of that hidden field and act upon that. The problem with that is that once ScriptManager.RegisterStartupScript fires it doesn't wait for the JavaScript function to "finish", ie wait for the user to reply to the confirm(). So the value in the hidden control will always be empty because the code behind gets to the check of that control before the user has a chance to respond to the confirm(). So that's a no go.
Use ScriptManager.RegisterStartupScript in code behind to open up a new ASPX page that asks the user the question and then does all the work in response to the user's answer in that page. The problem then is to pass the object that the new ASPX page needs to do work on in response to the user's response.
I'm sure there are great solutions using Ajax or jQuery but this is a fairly simple function that shouldn't take too long to develop, so that is kind of out of scope for this.
Instead I'll go with a solution where I know what the user will respond to the question before they click the button. (While silently muttering under my breath: "It's 2019 and there's no good way to fire up a yes/no dialog from code behind in a .Net web project...". I need to get back to not working with web).

asp.net master page and viewstate

I have some values that are set on a master page and that I want to save across a postback. I then want these variable to be available to pages using that master page during their load events.
Easy enough to create properties on the master page. So my first try to was to say that during the master page's load event, if not ispostback then generate the values and save them to the viewstate, else read them from the viewstate.
Except ... apparently the regular page load event happens BEFORE the master page load event, so the data wasn't there yet when I tried to read it.
Second try: have the master page set or retrieve these values during the Init event. No luck. Appears that the view state is not populated by Init time.
As far as I can tell, there's no event on a master page that happens after view state is populated but before the main page's Load event.
I suppose each page could have an InitComplete or PreLoad that calls a function to populate these fields, but that seems really clumsy. The call would have to be in every page. And it would have to be in every page even if that page never used this data, because the master page uses the data for its own purposes.
Is there a way to do this? Maybe view state is not the right place to save the data? I could store the data in Session variables, but then on not-postback the data in them would be left over from the last call. I guess I could make sure to clear the obsolete data, but that seems really clumsy.
I'm writing in VB but I wouldn't think that would make a difference here.
You could override LoadViewState method of the master page in the following manner:
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
// use the loaded values, if any, here
}
LoadViewState is called before Load and in fact even before PreLoad of the page, so that seems to fit what you are looking for.

reload current page in asp.net

I have a session variable that changes some things about how a page looks. I have a button that changes the value of this session variable. But ... the onClick event happens after page load, so by the time I update the session variable based on the button click, it's too late, the page has already been loaded.
Theoretically I could put all the logic about changing the display into a function and call it from page load, and then call it again from the onclick after the variable as been updated. But this is impractical: there are many user controls that check the value, used on many different pages in different combinations. I would have to hard-code the list of user controls on each page, and if someone added a new user control to a particular page, they'd have to remember to update this function, which is lame.
Is there a way to force a page reload? (I can use response.redirect back to myself and it works. If all else fails I guess this is what I'll do. But it means an extra round trip to the server, which is clumsy.)
Is there a way to process the onclick before the page load?
Some other magic solution?
If you have to change the look and feel of a page based on a specific value which can change, then you should have dedicated functions that set up the look and feel in a single unified place, and then you call those functions in every case where a value that affects the look and feel is called.
Examples:
private void SetDivVisibility()
{
// display logic here based on variables
}
private void MyControl_Click(...)
{
myvalue = blah;
SetDivVisibility();
}
It helps to bear in mind that the actual rendering of the page is last thing that happens, after both page load AND event processing.
Theoretically I could put all the logic about changing the display into a function and call it from page load
That's how you should do it. Cleanup your logic and markup - refactor and keep it DRY. That should help.
I can use response.redirect back to myself
That's the other option. Yes, a round trip is nasty.
you may put your code of styling your page in a void called by the page_load normally and called again from buttonclick
or call response.redirect to same url
or even onClick is client side use window.location.href
A design with a layout predicated on the existence of a session variable which won't exist until after it's been render is a huge design error. I like to call it the "Chicken or the Egg" syndrome. (yes, you can quote me.. ;)
I'd argue that your controls shouldn't get their layout completed in the on render. Instead, use a method (similar to databinding) where you can "rebind" the controls with the new session value on demand. This method would show/hide things based on the updated values.

ASP.NET How to raise load event on previous page with cross page postbacks

I'm working on a wizard-like set of page, and I'm relying on cross page postbacks to navigate between them.
I need to be able to trigger the Load event on the previous page in order to save the form data for the page.
I've been told that for situations of this sort all I had to do is access the PreviousPage property in the destination page and this would trigger the load event of the previous page but for some reason this doesn't seem to be working.
Is there anything else I can do to explicitly trigger the load event on the previouspage if the PreviousPage property is not null?
Thanks for your help,
Yong
Have you considered moving whatever persistence logic you're doing in the load of the Previous Page into a method on the page?
That way you can just hit:
if(PreviousPage != null)
PreviousPage.DoThatSavingThing();
Obviously you'd need to type it to get the specific methods you add unless you added those to all pages.
This sounds a little confusing to me, but if you are wanting access to data, it's best to save that data into something that you can easily get to, like the ASP.NET session cache. So instead of going back to a previously navigated page in order to get data, you will cache the data the first time you reach the first page, and then when the user navigates to the 2nd page, it will have access to that information.
To add - I tested using two methods of getting a "strongly-typed" previouspage.
Added a reference to the destination:
Added the PreviousPage directive on the destination:
When accessing the PreviousPage property in the destination, the Load event was fired on the
PreviousPageName page (source).
Example (assuming there is a public property named Test on the PreviousPageName (Source page)):
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
//Using a reference, you have to cast:
PreviousPageName x = (PreviousPageName)PreviousPage;
string test = x.Test;
//Using the PreviousPage directive, you do not need to cast:
string test2 = PreviousPage.Test
}
}

How can I reset a asp.net form after postback?

I am trying after the btnCreate_OnClick event to reset the form to it's default value just like the first page_load. The problem is after PostBack, every textbox and other controls, reloads the ViewState value. I cannot deactivate viewstate because of server event on DropDownList selection. The only way I found so far is to Redirect to self after the click event, but this loads the page twice and is therefor a bad solution. I have try ViewState.Clear() and update the UpdatePanel, but was unsuccessful.
I could do a loop for all controls and set the txtXXXXX.Text == "", but I'm quite sure it's not the best idea.
Something like Page.Reset() would have been just perfect but it doesn't exist.
Any thought on this problem of mine?
Thanks
If workable, I usually just use Response.Redirect to reload the same page from scratch.
An initial GET request to a page usually costs less than subsequent POSTs anyway, so there's not much reason to avoid it.
We can reset the ASP.NET Form Page with just 2 lines of code
protected void Button_Reset_Click(object sender, EventArgs e)
{
Session["ViewState"] = null;
Response.Redirect("/Roster/DRAC/Create.aspx");
}
Self redirecting gets tricky because of viewstate.
There is an html input type "reset" for buttons, but I'm not sure what or any integration msft has put into viewstate/asp.net for this. It generally works for simple javascript forms.
ex:
<input type="button" value="Reset" onclick="document.<formId>.reset();">
from google ----^
One way, not necessarily ideal, is to reset the values to their defaults using Javascript. If it is a large form, it can be ugly, but will prevent the need to do a self-redirection.
You also might try Server.Transfer instead of Response.Redirect(/self/)
I dont know if this helps but i change the name of every input on the form that i want to get fresh values by using javascript before submiting the form, since the .net page can no longer match the values from the form to the controls for the page it reloads them as if there was no postback. i also append a new value to the form so i know what button submitted the form and use that logic to decide what to load into all the controls and how to process the form data of course.
$("#Bset").children().click(function() { //all the btns click function
$.each($("form").find("input"), function(e,v) { //could filter this to subset of inputs
$(v).attr("name", "_" + $(v).attr("name")); // ctrl1 becomes _cntrl1
});
$("form").append("<input type='hidden' id='b' name='b' value='" + $(this).text() + "' />").submit();
});
then in the code behind
protected void Page_Init(object sender, EventArgs e)
{
id = int.Parse(Request.QueryString["id"]);
bk = db.dc.getDetailBK(id).Single();
if (Request.Form.Count > 0)
doPostBack();
mrl = (from a in db.dc.getMetricQTD(id, null, null, loadSavedGoals) select a).ToList();
}
i can then do things in dopostback that process the form data, interact with the db etc. that may change the values mrl is loaded with and refresh the data in the inputs tied to mrl regardless of wether they were modified or not on the form.
the other alternative would be to tie some buttons to use a webservice to handle your db interaction then call window.location to refresh the page.
$.ajax({
url: "webservice/dbfunction?"
data: {which btn pressed, some form values etc...}
success: function() {window.location("samepage.aspx?id=xxx");}
...
});
this would also avoid having to response redirect on the server side.
In our case the best performance solution was to set manually for each control the default value in the click event ex:
textbox1.Text = null;
textbox2.Text = null;
This avoid the double page_load and the loop. We don't event have to update the UpdatePanel since it executes before render.
Maybe in a more complex web application we would have to Redirect as most people seem to accept this as a solution.
Setting per control the default value was better suited to our case.
Thank you

Resources