IE and Firefox different postback Behavior after Server.Transfer - c#

I have 2 aspx pages, in a postback event from page 1, i add data to the current context, then do a server.transfer to page 2. this all works as expected, however due to the server.transfer, the address bar still shows the url for page 1.
the weirdness comes when i click a button on page 2.
in IE (7 or 8) when i click a button on page 2, the page posts to page 2 as expected.
in Firefox when i click a button on page 2, the page posts to page 1.
Has anyone else experienced this?
Am i doing something wrong?
Is there a workaround?
this is essentially the code in page 1
Context.Items["x"] = x.Checked;
Context.Items["y"] = y.Checked;
Context.Items["z"] = z.Checked;
Server.Transfer( "page2.aspx", false );

Do a cross-page postback instead?
MSDN: Cross-Page Posting in ASP.NET

If you're not using PreviousPage, you could use Response.Redirect("~/Page2.aspx"); instead. This will inform the user's browser of the page change.
Alternatively, if you are using PreviousPage use a cross-page post back by setting the PostBackUrl attribute on the desired Button. This will allow your Server.Transfer logic to be properly handled. To get access to the CheckBox's value you will need to make public properties on Page1 that will be accessible through the PreviousPage.
So Page1 will contain these properties in the code behind:
public bool xChecked { get x.Checked; }
public bool yChecked { get y.Checked; }
public bool zChecked { get z.Checked; }
Page2 will use PreviousPage:
protected void Page_Load()
{
if(PreviousPage != null && PreviousPage is Page1)
{
if(((Page1)PreviousPage).xChecked)
{
//use xChecked like this
}
}
}

You could try setting the form.action to the specific page you want to post to.
page 2's Form Load Event:
Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.Form.Action = "page2.aspx"
End Sub
This should guaranty posting to the correct page.

Related

Two postback buttons ASP.NET

I have two simple pages. Page 1 postbacks to page 2. I have two buttons that can cause a postback, Confirm and Delete. On page 2 there are two buttons; one saves the passed data, and the other deletes the passed data. What I need to do is have the unneeded button on page 2 set to visible = false. How can I set up different actions based on which button caused the postback?
you could use Query string to indicate the page to show the appropriate button in your second page
ex : http:\localhost\page1.aspx?show=delete
at the other hand, in your page2 "page_load" function you could manage the code to show the button based on query string requested along with the request url
the code will be something like this on your Page_Load:
string showButton = Request.QueryString["show"];
if(showButton == "delete")
{
// write the code to show the delete button here
}

ASP.NET: How to handle all page redirection?

In an ASP.NET page, are there any practical ways to handle all of these following:
PostBack
Redirection when user click a link in the page
Redirection when user change url field in the browser
with just a single web control (or method)?
TQ
Postback can be handled on the Server Side
the two others - link click or url field are ought to be handled using Javascript only.
UPDATE:
You can use jQuery to show a "loading animation" as mentioned in the question
$(window).unload( function () { alert("Bye now!"); } );
This will issue an alert once the user tries to leave the page. you can change it so it will display an animating gif image.
This must be tested though. I think it's pointless; not too sure on how long the gif will be displayed until the browser starts to load up the new page.
EDIT:
As I mentioned in comments, you can issue a postback using javascript
so, according to my last edit
$(window).unload( function () { __doPostBack("leaving"); } );
will issue a postback to the server, and you can catch it by:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
this.PreLoad += (sender, args) =>
{
this.ClientScript.GetPostBackEventReference(this, "arg");
if (!IsPostBack) { return; }
string __targetaction = this.Request["__EVENTTARGET"];
string __args = this.Request["__EVENTARGUMENT"];
if (string.IsNullOrEmpty(__args)) return;
if (__targetaction == "leaving")
{
doSomething();
}
};
}
then again, I'm not too sure this will be too helpful, since the user is leaving the page.
PostBack
In this Page.IsPostBack will be = true
Redirection when user click a link in the page
In this case you will get value in referrer. You can use Request.ServerVariables["http_referer"] OR Request.UrlReferrer
Redirection when user change url field in the browser
Else this is the 3rd case

How to open the page in new window using response.redirect in c#

Can anybody suggest how we can open the page in new window using Response.Redirect in c#, I know we can do it using response.write as given below:
Response.Write("<script>");
Response.Write("window.open('"+url+"','_blank')");
Response.Write("</script>");
But what when javascript is disabled, the above code will not run.
Please suggest!!
Response.redirect can't open a new window, it redirects the clients HTTP request to a new location in the current browser window. This is a limitation of server side, to perform a popup on the client machine you will at some point require client side code (IE, Javascript).
If you can settle for using a ASP:Hyperlink rather than a ASP:Linkbutton or ASP:Button you can handle the navigation a bit easier. Rather than using Response.Redirect during a postback, just build the hyperlink's NavigateURL during Page_Load or some other event:
protected void Page_Load (object sender, EventArgs e)
{
lnkViewPage.NavigateURL = sURL;
lnkViewPage.Target = "_blank";
}
Of course it is more polite to leave .Target alone because unlike buttons, linkbuttons, and imagebuttons, hyperlinks can be right clicked and "open in new page/tab" would be available from the context menu, giving the user control of how to handle the navigation.
As Tom Gullen suggested that is the only way.
I am assuming you're using ASP.NET.
You can create a public function which receives the Url you want to open in the new windows.
This function then redirects to a page which does the dirty job.
Public Function ResponseRedirect(ByVal urlRedirect As String) As Boolean
HttpContext.Current.Response.Redirect("Redirector.aspx?goto=" & HttpUtility.UrlEncode(urlRedirect))
End Function
This is Redirector.aspx
Public Partial Class Redirector
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim OpenNewPage As String = ""
If Request.QueryString("goto") IsNot Nothing Then
Me.OpenNewPage = Request.QueryString("goto")
End If
If Request.UrlReferrer.AbsoluteUri IsNot Nothing Then
Me.Referer = Request.UrlReferrer.AbsoluteUri
End If
End Sub
Private _OpenNewPage As String = ""
Public Property OpenNewPage() As String
Get
Return _OpenNewPage
End Get
Set(ByVal value As String)
_OpenNewPage = value
End Set
End Property
Private _Referer As String = ""
Public Property Referer() As String
Get
Return _Referer
End Get
Set(ByVal value As String)
_Referer = value
End Set
End Property
End Class
and the HTML of Redirector.asp
<script type="text/javascript">
window.open('<%=Me.OpenNewPage%>', '_blank', '');
window.document.location.href = '<%=Me.Referer%>';
</script>
It's not really really elegant code but it does the trick.
Obviously, if javascript is disabled it doesn't work.
I've put together a sample here.
Hope it helps.
There is no way to dynamically open a new window without javascript.
If you want the window to always redirect you can pass back HTML that tells the browser to redirect in the header information. Like so:
<META HTTP-EQUIV="Refresh" CONTENT="5; URL=html-redirect.html">
Remember this will basically happen right away (or in the case above in 5 seconds). If you want something to cause the page to go somewhere else without javascript you need a link the user clicks on.
You can add this dynamically in C# like this:
Dim reMetaTag As New HtmlMeta
reMetaTag.HttpEquiv = "Refresh"
reMetaTag.Content = "5;URL=http://www.site.com"
Page.Header.Controls.Add(reMetaTag)
If you want to disable javascript and still be able to open a window i suggest you to become a magician.
Using javascript and response.redirect for a server button(for example) without refreshing parent window you should use the following code:
<input type="button" id="Example" value="Click!" runat="server"
onclick="var win = window.open('','Stack','width=500,height=600,menubar=no');
document.forms[0].target = 'Stack';" onserverclick="Save" />
Save function defined in your page behind code would be something like this
protected void Save(object sender, EventArgs e)
{
//your code here
Response.Redirect(url);//url it's a string for target url
}
So Tom Gullen was wrong and Manu's idea would give you a headache because it refreshes parent page.
Hope this helps somebody. :)
if you are using http then use below code
Response.Write("<script>window.open ('URL','_blank');</script>");
this code cannot be used for https for https do below
javascript in page
function shwwindow(myurl) {
window.open(myurl, '_blank');
}
in c# code behind
string URL = ResolveClientUrl("~") + "**internal page path**";
ScriptManager.RegisterStartupScript(this, this.GetType(), "show window",
"shwwindow('"+URL+"');", true);
this code cannot bybass the browser popup blocker. user must allow it to run. for ie it opens in new window or new tab up to ie version in firefox and chrome it opens new tab
enjoy it!!

page_load event in Master and Content Pages

Here is the sequence in which events occur when a master page is merged with a content page:
http://msdn.microsoft.com/en-us/library/dct97kc3.aspx
So, my problem is:
I have one login page (not use master page), one master page, and hundreds of content page.
I check login session Session["loggedInUser"] in master page (if not logged in, redirect to login page)
So, when I don't log in, if I type the address of one content page, it must check login session in master page and redirect to login page, right? But it has two cases here:
If in content page, I don't use anything related to Session["loggedInUser"], it will redirect to login page, so, it's OK here!
The second case: if I use Session["loggedInUser"] to display Username in content page for example:
UserInfo loggedInUser = (UserInfo)Session["loggedInUser"];
it will return null object here, because the page_load in content page is fired before page_load in master page, so it thows null object instead of redirecting to login page.
I also tried Page_PreInit in master page but no help
protected void Page_PreInit(object sender, EventArgs e)
{
if (Session["loggedInUser"] == null)
{
Response.Redirect("~/Login.aspx");
}
}
Any suggestion?
Presumably, when you say you are using the Session["loggedInUser"] value, you are then calling .ToString() method or similar to display it?
In which case, you will need to check for a null object before using it. It would be best practice to check for the existance of the object before using any methods on it in any case, so:
if (Session["loggedInUser"] != null)
{ ... }
Only if you are certain that the code will never be executed without the Session object being instantiated can you use methods without checking for a null reference.
http://msdn.microsoft.com/en-us/library/03sekbw5.aspx
Finally I've come up with a solution:
I create a class BasePage like this:
public class BasePage : System.Web.UI.Page
{
protected override void OnLoad(EventArgs e)
{
if (Session["loggedInUser"] == null)
{
Response.Redirect("~/Login.aspx");
}
base.OnLoad(e);
}
}
And in the content page, instead of inheriting from Page, I change to BasePage and it works perfectly
Thanks for all of your support
Nice day ;)
You could check for Session["loggedInUser"] in the content Page's Page_PreRender() rather than Page_Load()or alternatively, do the master page check in the Page_Init() rather than Page_Load(). We had the same problem and went with the Master page Page_Init() option, so that we could still use Page_Load() in all the Content pages.
Edit: It's Page_Init() not PreInit().
I have 2 masterpages(1 for prelogin,2nd for afterlogin),home page is independent,logout page inherits postlogin page) in all postloginpage session chck if sessionnull(xyz)else(redirect loginpage) all this in Page_Init event of afterlogin.master................Successfull

Difference between "normal postback" and "page creation as PreviousPage"

There are two scenarios for an ASP.net webforms page which I would like to differentiate between: "Normal postback" and when a page is created because the next page has called PreviousPage.
A normal posback occured for page 1
IsPostback is true
IsCrossPagePostBack is false
and
There was a Server.Transfer("page2.aspx") to page 2, and page 2 uses PreviousPage so page 1 is created virtually. For page 1:
IsPostback is true
IsCrossPagePostBack is false
You can see that IsPostBack and IsCrossPagePostBack do not help because they are the same in both cases.
The reason why I am asking this:
I have page 1 which sends data to page 2 via cross-page postback (PostBackUrl="page2.aspx" set in page 1). For all users who have javascript enabled, this works fine.
But I wanted also a fallback for the users who have javascript disabled. For them, a click on the submit button on page 1 does not lead to page 2 but to a postback to page 1. Page 1 could now detect this and do a Server.Transfer("page2.aspx") to page 2. The problem is: When page 2 uses PreviousPage then page 1 is created again and would do a Server.Transfer() again and again and again ...
My workaround for this is to do the Server.Transfer not in the Page_Load event but only in the Page_PreRender event because this event does only occur when it is a normal postback and not when the page is created as PreviousPage.
This workaround works but it is very dirty. If I could differentiate between the two scenarios already in the Page_Load event, it would be much better.
Is this possible?
When you do the HttpServerUtility.Transfer from Page 1 to Page 2, the HttpContext is then shared between Page 1 and Page 2. So normally, one request means one request handler (usually a page) and one request context. But in this case there's two handlers and one (shared) context. You can use the context to share information about the request between the two handlers.
So one solution may be that Page 1 puts all the data that page 2 needs in the HttpContext.Items. Then Page 2 first checks for this data. If present, Page 2 knows that control was transferred by way of Server.Transfer and that it should not call on Page 1 through PreviousPage. Instead it should now get its data from the context.
Page1.aspx
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack && HttpContext.Items.Contains("CrossPagePostBack") == false)
{
// Cross page postback did not succeed (JavaScript disabled)
string name = NameTextBox.Text;
HttpContext.Items.Add("Name", name);
HttpContext.Items.Add("Transfer", true);
Server.Transfer("Page2.aspx");
}
}
Page2.aspx
protected void Page_Load()
{
if(IsPostBack)
{
string name;
if(CrossPagePostBack)
{
// Cross page postback succeeded (JavaScript was enabled)
HttpContext.Items.Add("CrossPagePostBack", true);
name = PreviousPage.NameTextBox.Text;
}
else if (HttpContext.Items.Contains("Transfer"))
{
// We got transferred to from Page1.aspx
name = (string)HttpContext.Items["Name"];
}
// Do something with Page 1's form value(s)
}
}
Or you can turn this around and let Page 2 add a mark ("Page 2 was here") to the HttpContext.Items, and then Page 1 checks that mark. If it's present it doesn't need to transfer again (break the loop). I'm not 100% sure if a call to PreviousPage also results in a shared request context.
Page1.aspx
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack && HttpContext.Items.Contains("CrossPagePostBack") == false)
{
// Cross page postback did not succeed (JavaScript disabled)
if(HttpContext.Items.Contains("Transfer"))
{
// We did not yet transfer to Page 2
HttpContext.Items.Add("Transfer", true);
Server.Transfer("Page2.aspx");
}
}
}
Page2.aspx
protected void Page_Load()
{
if(IsPostBack)
{
if(CrossPagePostback)
{
// Cross page postback succeeded (JavaScript enabled)
HttpContext.Items.Add("CrossPagePostBack", true);
}
string name = PreviousPage.NameTextBox.Text;
// Do something with Page 1's form value(s)
}
}
The second method is simpler in implementation, especially if the form on Page 1 is complex. You'd have only one place where you read Page 1's form, and you only add a simple boolean to the HttpContext.Items.

Categories

Resources