how to automatically redirect an ASP.NET page to another after 1 minute using c# code.
You can use something like this:
<meta http-equiv="Refresh" content="60; url=http://your.new/url/here" />
The "60" is the time in seconds to wait before page redirect.
Try this one line code:
Here 5 means redirecting after 5 seconds, and make it 60 if you want to redirect after 1 minute.
protected void btnRedirect_Click(object sender, EventArgs e)
{
Response.AddHeader("REFRESH", "5;URL=YourNextPage.aspx");
}
This code you can also put in Load event of the page so that it'll redirect to another page after loading current page.
You cannot use C# code to redirect after a certain time from the server side, since C# is executed on server side. You can do this by having the meta tag in your HTML:
<meta http-equiv="refresh" content="300; url=newlocation">
You can write code in C# to create this tag, Here is an example:
HtmlMeta meta = new HtmlMeta();
HtmlHead head = (HtmlHead)Page.Header;
meta.HttpEquiv= "refresh";
meta.Content = "300; url=newlocation";
head.Controls.Add(meta);
you can do so using:
System.Threading.Thread.Wait(60);
Response.Redirect("Somepage.aspx");
Edit:
System.Threading.Thread.SpinWait(60);
Response.Redirect("Somepage.aspx");
Note: The SpinWait parameter is a cycle count and not seconds as the above suggests.
Taken from MSDN page http://msdn.microsoft.com/en-us/library/system.threading.thread.spinwait.aspx
The SpinWait method is useful for implementing locks. Classes in the .NET Framework, such as Monitor and ReaderWriterLock, use this method internally. SpinWait essentially puts the processor into a very tight loop, with the loop count specified by the iterations parameter. The duration of the wait therefore depends on the speed of the processor.
There are many ways to do this but I love to use this code because it works well when used in many different circumstances.
HtmlMeta oScript = new HtmlMeta();
oScript.Attributes.Add("http-equiv", "REFRESH");
oScript.Attributes.Add("content", "60; url='http://www.myurl.com/'");
Page.Header.Controls.Add(oScript);
Doing this on the client would be better than doing it on the server.
You'll need to use javascript to setup a timer and then redirect.
See this on how to redirect:
How to redirect to another webpage in JavaScript/jQuery?
See this for timers:
Loop timer in javascript
http://www.w3schools.com/js/js_timing.asp
http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/
I love doing my stuff in JavaScript :-) I love JS. Here is my JS solution .
<script type="text/javascript"><!--
setTimeout('Redirect()',4000);
function Redirect()
{
location.href = 'your-redirect-to-link';
}
// --></script>
The page will be redirected after 4 minutes. You have to insert that into the head obviously.
Related
I have a program(c#) but the programs needs to work for every timezone, so i created a js script to know the client timezone and this is what i get (and it works) but only if only click action(example button), but i need this to work (run) on my page load is that possible?
This is my script
<script type="text/javascript">
function pageLoad() {
myFunction();
}
function myFunction() {
var localTime = new Date();
var year = localTime.getYear();
var month = localTime.getMonth() + 1;
var date = localTime.getDate();
var hours = localTime.getHours();
var minutes = localTime.getMinutes();
var seconds = localTime.getSeconds();
var calculated_date = hours + ":" + minutes + ":" + seconds;
var div = document.getElementById("demo");
div.innerText = calculated_date;
var client_date = document.getElementById("client_date");
client_date.setAttribute("value", calculated_date);
}
</script>
And this is what i tryed so far
Page.ClientScript.RegisterStartupScript(this.GetType(), "myFunction", "myFunction()", true);
Session["Data"] = client_date.Text;
Response.Redirect("Welcome.aspx");
Thanks anyway for reading my post, hope someone can help on this issue
Yes, it is possible. All you need is to use onload() event.
This would do it
<body onload="myFunction()">
<!-- body elements here -->
</body>
You can execute any function that you want to execute on a page load. I used myFunction because that had to be executed when the page loads.
with javascript
if (document.readyState === "complete") { myFunction(); }
with jquery
$(document).ready(function(){ myFunction(); });
The problem isn't what you think. In all likelihood, this JavaScript *is*set to run when the page loads. And it's probably going to do exactly what you told it to do. The problem is what else you're doing. Note these three lines:
Page.ClientScript.RegisterStartupScript(this.GetType(), "myFunction", "myFunction()", true);
Session["Data"] = client_date.Text;
Response.Redirect("Welcome.aspx");
What you're doing here is:
Set the JavaScript to run when the page loads.
Capture the value of a TextBox from before the page loaded.
Abandon the page entirely and redirect to another page.
So even if the JavaScript code would run, you're not capturing the value it sets. And even if you were capturing that value, you abandon the entire page before it even loads and redirect the user to a different page.
You need to better understand the difference between server-side code, which runs on the server in its entirety before delivering a page to the client... and client-side code, which runs after a page has loaded on the client.
If you need this information from the client, you'll need to get it from client-side code. This code will need to run in a loaded page and then send the value back to the server in some way. Either the page has to execute and then perform the redirect from client-side code, or (probably better) the page can run as normal, make an AJAX post to the server to notify you of this information (time zone), and then the server can respond to the AJAX request with any data the client-side code needs to adjust the page accordingly.
It's not really clear what you're customizing based on the time zone or when you need to know the time zone. But it is clear that you need the client-side code to execute before you can retrieve that value from the client.
Use System.Web.ScriptManager Like this :
Page.ClientScript.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "myFunction();", true);
Session["Data"] = client_date.Text;
Response.Redirect("Welcome.aspx");
Well you can't store the value within a hidden field and then read result, but what you can do is store the timezone offset as a cookie and then read that on the server after the page reloads.
This article explains it perfectly
http://prideparrot.com/blog/archive/2011/9/how_to_display_dates_and_times_in_clients_timezone
Please let me ask something. I just confused for what is the difference of javascript, JQuery and code behind attributes.
for example :
ASPX
<tbody id="toggleSup" runat="server">
C#
toggleSup.Visible = false;
--------------------------------------- OR ---------------------------
C#
CallScript((string)(Session["toggle"]));
private void CallScript(string str)
{
string scriptx = "<SCRIPT LANGUAGE='javascript'>";
scriptx += "toggle('" + str + "');";
scriptx += "</script>";
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "scriptx", scriptx, false);
}
Script
function toggle(para1) {
if (para1 == 0) {
$('#toggleSup').hide();
}
else {
$('#togglePO').hide();
}
}
for these two difference things, most of the developers use script. Why? Actually C# code is only one row. different thing is if I use script, no need to use runat="server" but if I used code behind, need to use runat = "server". So I think there may be definately have advantages. Please explain me, if possible...
Thanks
If you say toggleSup.Visible = false; in your C#, then the toggleSup does not even get rendered to the DOM. Meaning it's not on the page at all. If you want to make that element visible from some action on the page, then you have to make a round trip to the server and re-render all (postback) or part (ajax) of the page.
Alternatively, if you allow the toggleSub control to be manipulated from JavaScript (jQuery in this case), then it's part of the DOM and can be acted upon in response to other events on the page. Mainly, this means that the client browser can do things without asking the server for more HTML.
So, the C# method looks simpler to code, but the jQuery method is more flexible if you need a rich client-side experience.
When using "script", the browser performs the work. With runat server, then the browser must either get/post a HTTP request or do "AJAX" to the server.
Using "script" is much faster and is easier to maintain state.
In simple words Java Script and JQuery code runs on the client browser whereas C# code runs on the server.
I have used location.href to redirect next page, but now i want to back to this page, how can I do?
in my case, i cannot use Request.UrlReferrer.PathAndQuery, so any suggestion?
Since you are using location.href to change the URL, your browser is going to kick off a new request/response cycle. Thus to your server, there is no referrer - this is a whole new request.
The most direct approach to solve your problem would be to add a referrer-url parameter to your new URL, which you can then pick up on the server side.
eg:
control.location.href = "newpage.aspx?referrer-url=thispage.aspx";
and on the server:
string referrerUrl = Request["referrer-url"];
If the previous URL is one that you own/can predict (e.g. the user came from page A or page B), you could use a trick like this one: http://www.merchantos.com/blog/makebeta/tools/spyjax
When i POST the page using the following code, the Response.write("Hey") doesn't write the content ("Hey") to the parent page
<form method="post" name="upload" enctype="multipart/form-data"
action="http://localhost:2518/Web/CrossPage.aspx" >
<input type="file" name="filename" />
<input type="submit" value="Upload Data File" name="cmdSubmit" />
</form>
But When i use following code , and POST the data, the Response.write("Hey") can be obtained in the parent page
HttpWebRequest requestToSender = (HttpWebRequest)WebRequest.Create("http://localhost:2518/Web/CrossPage.aspx");
requestToSender.Method = "POST";
requestToSender.ContentType = "multipart/form-data";
HttpWebResponse responseFromSender = (HttpWebResponse)requestToSender.GetResponse();
string fromSender = string.Empty;
using (StreamReader responseReader = new StreamReader(responseFromSender.GetResponseStream()))
{
fromSender = responseReader.ReadToEnd();
}
In the CrossPage.aspx i have the following code
if (!Page.IsPostBack)
{
NameValueCollection postPageCollection = Request.Form;
foreach (string name in postPageCollection.AllKeys)
{
Response.Write(name + " " + postPageCollection[name]);
}
HttpFileCollection postCollection = Request.Files;
foreach (string name in postCollection.AllKeys)
{
HttpPostedFile aFile = postCollection[name];
aFile.SaveAs(Server.MapPath(".") + "/" + Path.GetFileName(aFile.FileName));
}
Response.Write("Hey");
}
I don't have any code in the Page_Load event of parent page.?
What could be the cause? I need to write the "hey" to the Parent page using the first scenario. Both the application are of different domain.
Edit: "Hey" would be from the CrossPage.aspx. I need to write this back to the Parent Page
when i post using the form action, after processing the Page_Load() event in CrossPage.aspx, the URL points to "http://localhost:2518/Web/CrossPage.aspx" which means the application is still in the CrossPage.aspx and didn't move to parent page.
You almost hit on the reason yourself:
when i post using the form action, after processing the Page_Load() event in CrossPage.aspx, the URL points to "http://localhost:2518/Web/CrossPage.aspx" which means the application is still in the CrossPage.aspx and didn't move to parent page.
Your form takes the user to CrossPage.aspx, so the parent page is gone, now the previous page in the user's history.
It sounds like you are trying to do some sort of asynchronous file upload. Try looking for AJAX file upload examples, something like this: How can I upload files asynchronously?
Probably it is because you have the code in an
if (!Page.IsPostBack) block? this code will be executed only the page is not loaded on a post-back.
(HttpWebResponse)requestToSender.GetResponse(); will trigger a GET request, that's why your code is working when you call Crosspage.aspx using that code.
You are treating the page like a service. E.G. Start at ParentPage.aspx > pass data to ServicePage.aspx for processing > write response back to ParentPage.aspx for display.
You got it to work with C# by passing the duty back to the server, where state can easily be maintained while crossing page boundries. It's not so simple when you try to solve the problem without C#. This isn't a Winform app. As NimsDotNet pointed out, changing the method to "get" will get you closer, but you will get redirected to CrossPage.aspx and lose the calling page.
You said you are on "different domains". By this I think you mean your using two different IIS servers. The C# solution should still work in this scenerio, just as you've shown. Just add a Response.Write() of the fromSender object. There's nothing you've told us that makes this not technically possible. Still, if you want a client side solution you could use javascript to make the get request without getting redirected.
This post shows you how to make a get request with JQuery.
I say your aFile.SaveAs(Server.MapPath(".") + "/".... is throwing an exception. try commenting it out and testing it.
UPDATE:
I'm guessing it works from a HttpWebRequest because there is no file being posted therefore the file loop is skipped. when posting from the HTML you have a file input so your file loop is getting used and resulting in the save logic being executed. so again, that leads me to think it's your save logic
Also,I think you have a try catch statement wrapped around all this that is catching exception so u have no idea what's going wrong. If that's the case, never do that. You rarely ever want to catch exception.
After quick glance at ur save logic, replace "/" with #"\". Server.MapPath(".") returns the path using back slashes not forward slashes.
I would suggest changing CrossPage.aspx into an .ashx HttpHandler. The Page.IsPostBack may not be working correctly because it is expecting ViewState and other hidden ASP.net form fields that tell it that it's a post back from an ASP form. You also don't need to go through the whole Page life cycle functionality that ASP.net Webforms goes through.
I need to refresh sections of my page to update when there is new data! what do i do? use jquery?
examples:
Yes, jQuery's great for this. Look into these methods:
http://api.jquery.com/category/ajax/
jQuery is usually not needed for basic AJAX. A simple example could be as follows:
liveSection = document.getElementById('latest-news');
request = new XMLHttpRequest;
request.open('GET', '/news-ajax', true);
request.send(null);
request.addEventListener('readystatechange', function() {
if (request.readyState == 4 && request.status == 200)
liveSection.innerHTML = request.responseText;
}, false);
If you're using Asp.NET, why not use an UpdatePanel? It's simple and reliable.
Edit
I just re-read your question and it looks (based on how you worded it) that you want to update a user's web page when the data changes on the server. I just want to make sure you understand that in a web app, the server can't trigger the browser to do anything. The server can only respond to browser requests, so you'll need to have the browser poll the server periodically.
I've created a simple example (using jQuery) to help you understand the breakdown of the things that will need to happen, which are:
1 - Periodically polling the server (via ajax) using Javascript's setTimeout to check that what is loaded into the browser is the latest content. We can achieve this by fetching the latest item ID or whatever and comparing it to a variable, which was initialised when the page first loaded.
2 - If the item ID does not match (a bit of an oversimplification) then we can assume that there has been an update, so we replace the content of some element with some content from some page.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
function getLatestStuff() {
// fetch the output from a context which gives us the latest id
$.get("isthereanupdate.aspx", function(response) {
// we have the response, now compare to the stored value
if(resp != lastItemId) {
// it's different, so update the variable and grab the latest content
lastItemId = response;
$("#latestStuffDiv").load("updates.aspx");
}
});
}
$(document).ready(function() {
// the value which initializes this comes from the server
var lastItemId = 7;
setTimeout(getLatestStuff, 10000);
});
</script>
If you want to update when there is new data, you should look into comet or pubsubhubbub. jQuery can help you display the data in a pretty way, but you'll need to write stuff on the serverside to send the data.