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
Related
I used server.execute to hide my query string in URL, but I found another problem, when I'm in page 1 and clicks a button that transfers me to page 2 , page 1 content is still displayed in the page with the content of page 2. Both pages are shown to me. How can I resolve this ?
example of my code. in page 1 , there is a button, I add this code in click event.
protected void Button1_Click(object sender, EventArgs e)
{
Server.Execute("Page2.aspx?Name=john");
}
in page 2 , there is a text box that reads the query string value.
TextBox1.Text = Request.QueryString["Name"].ToString();
I send multiple values in query string but this is just an example. however, page 1 and page 2 contents are both displayed in one page after clicking the button that should transfer me to page 2.
Use Server.Transfer instead of Server.Execute.
Check this out to understand the difference.
Difference between both
When Server.Execute is used, a URL is passed to it as a parameter, and the control moves to this new page. Execution of code happens on the new page. Once code execution gets over, the control returns to the initial page, just after where it was called. However, in the case of Server.Transfer, it works very much the same, the difference being the execution stops at the new page itself (means the control is'nt returned to the calling page).
In both the cases, the URL in the browser remains the first page url (does'nt refresh to the new page URL) as the browser is'nt requested to do so.
As server.execute transfer control back to original page and continue execution of it also, therefor you are seeing output of both pages. To Transfer the request completely use Server.TransferRequest
Page1.aspx : add query string values as NameValueCollection
NameValueCollection nv = new NameValueCollection();
nv.Add("Name","john");
Server.TransferRequest("Page2.aspx",true,"GET", nv);
Page2.aspx : get your values from Request.Header
TextBox1.Text = Request.Headers.Get("Name");
Here a button that does a postback
<asp:LinkButton runat="server" ID="btnBestPrice" OnClick="btnSearchBestPrice_Click">Search Best Price</asp:LinkButton>
Assume that this button is clicked on page
http://localhost:47207/Default?ClusterId=131
Now after the postback is completed, the page is still
http://localhost:47207/Default?ClusterId=131
However, after the postback, i want to make URL to be
http://localhost:47207/Default
Is that possible?
If i make a redirect, the postback event would be loss. I still want to process the postback event perfectly fine. So if somehow i can set the postback url to be raw url of the page on the client side or?
asp.net 4.5 web forms c#
I assume your postback is displaying some information to user, but have to change the URL without interrupt the process.
First of all you have to understand that if you changed the URL in the server side, the browser will treat it as a new page and make a new request. Response.Redirect is basically telling the browser it is time to move onto another page. So you cannot change the URL while remaining in the same request. (while Server.Transfer is remaining at the same URL but different page which is not what you want)
So I have 2 solutions for you, the following one make sense to me but there is still redirecting the page:
protected void Page_Load(object sender, EventArgs e) {
if (Session["ClusterId"] != null) {
try {
int ClusterId = int.Parse(Session["ClusterId"]);
// Code here
} catch { }
Session.Remove("ClusterId");
return;
}
}
protected void btnSearchBestPrice_Click(object sender, EventArgs e) {
int ClusterId = int.Parse(Request["ClusterId"]);
Session.Add("ClusterId", ClusterId.ToString());
Response.Redirect("~/Default");
}
Here is another solution that does all the actions in your btnSearchBestPrice_Click event without Redirect and Session, and bind a JavaScript page ready event, call history.pushState and also wipe out the unnecessary parameters in the action attribute of your form element.
I'm fairly new to ASP.NET, I've been reading a few questions related to this but I'm still unable to figure out what's wrong with my code, I have a default.aspx page with a menu on top created using a list (ul and li items) and putting the <a href=""> tag to create the links to other pages but after following a link to another page, the Page_Load event fires before leaving the page, I understand this would be the expected behavior with Response.Redirect, but I don't know how to avoid this using tags (if possible), this is the markup I'm using for the Default.aspx page:
<ul id="lista">
<li><strong>Inicio</strong></li>
<li><strong>Item</strong></li>
<li><strong>IK</strong></li>
<li><strong>Acerca de</strong></li>
</ul>
And this is the code behind I have for Page_Load:
protected void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
ExcelUtility excel = new ExcelUtility();
dtDefault = excel.LeerExcel();
gridResults.DataSource = dtDefault;
gridResults.DataBind();
gridResults.VirtualItemCount = dtDefault.Rows.Count;
}
}
Basically, what I want to do is to follow the link to some other page without loading the default page before leaving, hope I make myself clear!
Edit: The root cause of this was having the default <form runat="server"> tag at the beginning of the body section, this was causing the Page_Load event firing again in the same page once the links were being clicked, placing the hyperlinks outside of the form tag did the trick.
Your HTML code should be inside some HTML tag or custom ASP control which contains the attribute runat="server". This is supposed to fire a PostBack request to the server.
I declared in master page load:
Session["sessionString"] = "stringX";
in my web page on load also, i call it
string sessionString= (string)Session["sessionString"];
i debug and value in web page is "" what is wrong?
The Page_Load event of a content page is called before the Page_Load event of the master page (see this SO answer and MSDN article). Hence, when you call
string sessionString= (string)Session["sessionString"];
in your web page, Session["sessionString"] does not contain any value yet and defaults to an empty string.
As a workaround, you could set the value of Session["sessionString"] on the Init or PreLoad events of your master page.
JW Lim is correct...content page's load event will fire before Master page load.
#user3445314 , you can use "Session_Start" event in Global.asax and set values same as you set in master page.
"Session_Start" event fires first and then your content page load event occur.
I hope this may be solve your problem
Declare Session in Master PreRender
protected override void OnPreRender(EventArgs e)
{
Session["sessionString"] = "stringX";
}
And get it by ContetPage OnUnload event
protected override void OnUnload(EventArgs e)
{
string sessionString= (string)Session["sessionString"];
}
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.