Button Click To Send To New Page - c#

I have tried both Response.Redirect and Server.Transfer to take me to a new page on button click, but every time my page just refreshes and I am never redirected to the new page. I have verified the page exists in my project and even copied/pasted the name of the page into my syntax to make sure no weird spaces or anything, but I NEVER get redirected
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
filldropdowns();
}
}
protected void btn1_OnClick(object sender, EventArgs e)
{
Response.Redirect("page2.aspx");
Server.Transfer("page2.aspx");
}
<div id="btn11" algn="center">
<asp:Button ID="ClickBtn1" runat="server" Text="Push Me" OnClick="btn1_OnClick" OnClientClick="return ValidateData();" />
</div>
<script type="text/javascript">
function ValidateData() {
var name;
name = document.getElementById("txtName").value;
if (name == '' || name.trim() == '') {
alert("Please enter a valid name");
return false;
}
}
</script>
EDIT
using the ~/ will allow a redirect but it throws the below error. The page does exist!
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /page2.aspx
EDIT 2
This is the markup for my page2 if that matters
<%# Page Language="C#" AutoEventWireup="true" CodeFile="page2.aspx.cs" Inherits="page2" %>
And if I use localhost in my redirect it loads no problem, but I am ready to push this out into the interweavings of the web and can not use localhost anymore. What should I change this to?
http://localhost:1444/TestProject/page2.aspx
EDIT 3
If it helps (or matters) the full location to the .aspx page that I want to redirect to is this:
C:\Users\Habib\Documents\Visual Studio 2015\Projects\Test\TestProject\Page2.aspx

You have shown syntax that is known to work whether it be means of Response.Redirect() or Server.Transfer() those methods are tried and true to be successful. If when you step through your code it hits your break point for the re-direct, then show us what you have in your Page_Load() for page2.aspx.
And we can help further diagnose and/or troubleshoot from that.

Related

pass data from client side to server before page_load executes

A button on html page redirect to aspx page with window.open() command.
There are certain data on the html page which i want on server-side of the aspx page before page_load executes.
following is my code on the html page which redirects to the aspx page
var win = window.open('mypage.aspx','_self');
win.args=this.Args;
following is my code on aspx page which tries to catch the data passed from the html page
<script type='text/javascript'>
var readyStateCheckInterval = setInterval(function () {
if (document.readyState === "loading") {
$('#hdnArgs').val(window.args);
clearInterval(readyStateCheckInterval);
}
}, 100);
</script>
<input type='hidden' id='hdnArgs' runat='server'/>
Following is the code on the aspx.cs file which tries to read the hidden variable's value which has been set from the data of the html page
protected void Page_Load(object sender, eventargs e)
{
string data = hdnArgs.value; //this is always null
}
But what I get is always 'null'.
The readyStateCheckInterval sets the hidden variable value after the page_load event is completed.
I want the value of hidden variable before page_load.
How can I get that?
Its not possible to set value of any control before page life cycle finish.
let me explain you..
You try to set value on hdnArgs but In Page lifecycle control only generate and send it to browser only after finish Page_init,Page_Load,Page_Load_Complete
All those methods..
So,When you try set args value to hdnArgs using $('#hdnArgs').val(window.args); Page_load event already completed..
Solution
I think you need to pass value as a QueryString to get Value in Page_load
var win = window.open('mypage.aspx?Args='+this.Args,'_self');
and In ASPX page
protected void Page_Load(object sender, eventargs e)
{
string data = Request.QueryString["Args"];
}
Also you can send data using Page Postback if you have large data.
To confirm:
hdnArgs is on the starting page
starting page opens a new page in a window
when that page is opening (but not complete, which will hopefully happen when you happen to look at it at 100ms intervals... it won't if it's quicker than that), input#hdnArgs is updated to the a value from the opened page
The Page_Load is on the starting page
You want the start page Page_Load to get a value from the popup
You'll need to review the lifecycle of asp.net pages, eg: https://msdn.microsoft.com/en-gb/library/ms178472%28v=vs.100%29.aspx
By the time the start page even thinks about processing any javascript, the Page_Load of the startup page is long gone.
Perhaps, in the Page_Load, you could load the new page directly eg with
var content = new System.Net.WebClient().DownloadString(contentUrl);
and parsing it for the #hvnArgs

Page_Load method running twice

I have created a VS 2013 project using built-in asp.net Web Application Web Forms template. By putting a breakpoint in the Page_Load method of a page I can see the method is executed twice between pressing F5 and the page appearing. Why? And can I / should I stop this behaviour?
Apologies for not providing enough detail. The code is completely vanilla, untouched template code generated by VS Exp 2013 for Web.
The ASPX file is
<%# Page Title="About" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="About.aspx.cs" Inherits="mycompanyname.B1WebApp.About" %>
The ~/Site.Master has an empty Page_Load method (not sure this is relevant)
The code behind is
public partial class About : Page
{
protected void Page_Load(object sender, EventArgs e)
{
Boolean Nothing;
}
}
You can avoid pageload function working on each postbacks by !IsPostBack
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Your code here
}
}
A User control with this master page can also cause pageload execute twice...
This is part asp.net web forms, as a page posts back to itself whenever a server control is used on a page. It has been like this forever.
You need to do a check on page load:
if(!IsPostBack)
{
//Code for first time load
}
else
{
// code whenever you have a postback
}

Stop redirect page on back button click

I'm trying to remove history for a particular site. When I'm logout the page and then press back button, the page move in previous page but I want when any user logout and then press back button it will be on same page that is login page not go in previous page. I'm trying all method like session abandon, cache remove but my problem not solved. We can also use JavaScript.
protected void btnLogout_Click(object sender, EventArgs e)
{
HttpContext.Current.Cache.Remove("");
HttpContext.Current.Session.Clear();
HttpContext.Current.Session.Abandon();
Response.Redirect("../Login.aspx");
}
You can try using javascript:
<script type="text/javascript">
//Logout clears all visited pages for Back Button
function noBack() { window.history.forward(); }
noBack();
window.onload = noBack;
window.onpageshow = function (evt) { if (evt.persisted) noBack(); }
window.onunload = function () { void (0); }
</script>
If page is served using cache then do the below things to set the proper http headers
HttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
HttpContext.Current.Response.Cache.SetValidUntilExpires(false);
HttpContext.Current.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetNoStore();
You've two options:
Prevent page from being cached
Prevent user from going back to previous page after he logs out using JavaScript.
I would suggest the first one but if it doesn't work for you, go for the second option as mentioned here
From what I see, it looks like you are handling people logged on by session variables. If that is the case, then in the master page or a base page couldn't you check to make sure that person is logged on by checking the presence of a certain session variable? If they are logged on, continue as normal, if not then you could redirect them back to the logon page (or default) to make them log on?
In the code behind add the below code
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
string strDisAbleBackButton;
strDisAbleBackButton = "<script language=\"javascript\">\n";
strDisAbleBackButton += "window.history.forward(1);\n";
strDisAbleBackButton += "\n</script>";
ClientScript.RegisterClientScriptBlock(this.Page.GetType(), "clientScript", strDisAbleBackButton);
}
protected void Page_Init(object Sender, EventArgs e)
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1));
Response.Cache.SetNoStore();
}
Hope the above code will work for you.
Use react and then, useEffect to have constant looping default such as /page=0 or /login added to the path say /accounts/login/login so when they click back it will just re-route to the same page as it can't go back, because its an infinite loop.
This question has been asked several times in stack overflow.A simple search would get you a solution.
After logout you have to disable back button.for that you have to use
Page.Response.Cache.SetCacheability(HttpCacheability.NoCache)
Removing cache itself will stop navigating backwards.

How to redirect browser during an Async Postback?

The scenario
I have an ASP.NET project which uses a custom authorization/authentication method (vs. using forms/windows authentication, etc.). On each secure page load, the following code is executed:
protected void Page_Load(Object sender, EventArgs e)
{
if (!IsLoggedIn)
{
HttpContext.Current.Response.Redirect("~/Login/", true);
}
}
This code basically checks whether the user is still logged in (no expired ASP.NET session, not logged out, etc.); if the user is not logged in, a Response.Redirect() happens, sending them to the login page.
This scenario works perfectly fine when the user requests a full page (through a link, or direct URL). The issue arises when using an async postback!
I have a button nested inside of an <asp:UpdatePanel>, which cause async postbacks when clicked. This button updates an <asp:Label />. For example:
<!-- the button -->
<asp:LinkButton ID="MyButton" CausesValidation="false" Text="My Button" OnClick="MyButton_Click" runat="server" />
<!-- the label -->
<asp:Label ID="MyLabel" runat="server" />
protected void MyButton_Click(Object sender, EventArgs e)
{
MyLabel.Text = DateTime.Now.ToString();
}
The issue
When an async postback is executing, and IsLoggedIn is false, the request is redirected to the login page. Now, the ASP.NET Framework expects a specific response (rather than an HTML page); thus, throwing the following error:
The question
How can I solve this issue? How can I force the whole page redirect to a specific address from the code-behind during an async postback?
While Kenneth's answer is the appropriate method of redirecting, I needed something a little more custom.
During an async postback, I needed to simulate Response.Redirect("path", true) - the true parameter (Indicates whether execution of the current page should terminate) is the important thing I needed to replicate! Simply using Response.End() after ScriptManager.RegisterClientScriptBlock() would not work because then there would be no response sent back to the browser.
By analyzing the server response to an async postback, I resorted to using the following hack (simulating a response by using Response.Write):
String jsRedirect = String.Format("window.location.pathname = '{0}';", VirtualPathUtility.ToAbsolute(url));
Response.Write(
// required parameters!
"0|asyncPostBackControlIDs|||" +
"0|postBackControlIDs|||" +
"0|updatePanelIDs|||" +
"0|childUpdatePanelIDs|||" +
"0|panelsToRefreshIDs|||" +
// your custom JavaScript
String.Format("{0}|scriptBlock|ScriptContentNoTags|{1}|", jsRedirect.Length, jsRedirect)
);
Response.Flush();
Response.End();
If you want to trigger from the code-behind you can do this:
if (ScriptManager.GetCurrent(Page).IsInAsyncPostBack) {
ScriptManager.RegisterStartupScript(updatepanelid, typeof(string), "redirect", "window.location = 'http://www.google.com';", true);
} else {
Response.Redirect("http://www.google.com");
}
Also note that if you use window.open(), a popup window will be opened (which may or may not be blocked). If you use window.location = "someurl"; it will just do a client-side redirect.
There is some terminology misunderstanding here. "Async postback" is not technically a postback at all; it is an xmlHttpRequest. If you want to do a redirect here, it must be done in javascript in an ajax callback function using window.open().
I'm not sure how you would implement this using asp.net AJAX. During the execution of your xmlHttpRequest code on the server, it is impossible to redirect a client (clarification - you may redirect, but the html you respond with will be (as in your case) incorrectly parsed by asp.NET's javascript ajax code.
With jQuery, this would be a pseudo-solution.
$.ajax({
success: function(data) {
if (data == 'redirect') {
window.open('yourRedirectUrl');
}
}
});

NullReferenceException on ASP.NET PreviousPage Property

I followed the directions from MSDN on transferring data between asp.net pages.
But when using the 'PreviousPage' property to access the previous pages controls, I get a null ref exception that PreviousPage is not set to an instance of an object.
Here is my code:
public partial class Portal : System.Web.UI.Page
{
public string Username
{
get
{
return txt_User.Text;
}
}
And this is the submit button on initial page:
<asp:Button ID="btn_Submit" runat="server" onclick="btn_Submit_Click"
PostBackUrl="~/Query.aspx"
Previous page property on second page:
protected void Page_Load(object sender, EventArgs e)
{
Username = PreviousPage.Username;
}
As per MSDN instructions I also added this at the top of the second pages markup file:
<%# PreviousPageType VirtualPath="~/Portal.aspx" %>
Also note I have tried Server.Transfer to switch pages instead and that produces the same error.
EDIT, here is using Server.Transfer on the initial page click event:
protected void btn_Submit_Click(object sender, EventArgs e)
{
Server.Transfer("Query.aspx");
}
EDIT, button code without event handler:
<asp:Button ID="btn_Submit" runat="server"
PostBackUrl="~/Query.aspx"
style="height: 26px" Text="Submit" />
This works fine for me. If PreviousPage is null, that generally indicates the current page was not displayed as a result of a cross-page postback.
Can you confirm the error is being raised on the second page?
Also, what the onclick="btn_Submit_Click" in your button definition? There should be no code responding to the click event on the original page. Remember, it will be handled by the target page.
EDIT: Now that you've updated your question, my last point seems to be the issue. You are doing a server transfer from the original page. This is NOT a cross-page postback and that's why PreviousPage is null.
Remove the onclick attribute from your button and delete btn_Submit_Click.

Categories

Resources