How to preserve "post data" on redirect - asp.net

I want to redirect a post from /mynode to /eng/mynode/ and preserve form data.
I've tried "Server.Transfer" but I get an error saying "Error executing child request for /en/mynode".
I would like to implement this in a general fashion, for example in OnPreInit() method of base page.
Do you see any other options?
P.S. When you use Server.Transfer, "the page transferred to should be another .aspx page. For instance, a transfer to an .asp or .asmx page is not valid". See source.

I suppose you can write something like:
protected void Page_Load(object sender, EventArgs e) {
Response.Clear();
Response.Write(#"<html>");
Response.Write(#"<body>");
Response.Write(#"<form id=""form"" action=""/eng/mynode/"" method=""post"" enctype=""application/x-www-form-urlencoded"">");
for(int i = 0; i < Request.Form.Count; i++) {
var key = Request.Form.GetKey(i);
var values = Request.Form.GetValues(i);
foreach(var value in values) {
Response.Write(string.Format(#"<input type=""hidden"" name=""{0}"" value=""{1}"" />", key, Server.HtmlEncode(value)));
}
}
Response.Write(#"</form>");
Response.Write(#"<script>document.getElementById(""form"").submit();</script>");
Response.Write(#"</body>");
Response.Write(#"</html>");
}

Related

asp.net send the response about 15 minute

i want when the client send to my web page request,my web page get the request and active timer and wait about 15 minute and check client so connect and response the json string.
my server code is:
string name, count;
protected void Page_Load(object sender, EventArgs e)
{
name = Request.QueryString["name"];
count = Request.QueryString["count"];
Timer1.Interval = 15000;
Timer1.Enabled = true;
}
protected void Timer1_Tick(object sender, EventArgs e)
{
if (Response.IsClientConnected)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
string json=jss.Serialize("در خواست شما تایید شد");
Response.Clear();
Response.Write(json);
Response.End();
}
else
{
Response.End();
}
}
how can i do this?
From your comment : " thanks,i want for example customer send my server a order and when the system manager accept the order,response to client:your order accepted"
You will need to include jQuery to do this bit.
As you have the name and count in the query string, which I take it will help you identify the customer (or change it to an order ID), then you can use the following on your .aspx page in a javascript block:
$(document).ready(function(){
setTimeout(function()
{
location.reload();
}, (15 * 60 * 1000)); // (that's 15 mins that I couldn't be bothered to work out...)
});
Your server side code could then be:
protected void Page_Load(object sender, EventArgs e)
{
var name = Request.QueryString["name"];
var count = Request.QueryString["count"];
if(OrderAccepted(name, count))
{
// display message to user
}
}
private bool OrderAccepted(string name, string count)
{
// do what you need to do to find out if the order is accepted.
}
You may also want to try and have the javascript only run if the order is not accepted so that it doesn't keep running. But a 15 min interval is a decent long period, and most people will close their browsers once they know the order is accepted.
Hope this helps.
You cannot achieve what you are trying to do through "only" server-side (compiled C#) code.
The problem is that you want the client to send a request every fifteen minutes - to get the latest JSON - but you are trying to tell the server to do that.
There are many better ways to accomplish what you are trying to do (ie, better than a fifteen-minute timer) but here is one way you can achieve that through JavaScript:
First, expose your server's API call (the call that gets the JSON).
Then, in a script node on the client (ie in a script tag in the HTML you send down), define the following function:
function refreshDataAndUpdatePage() {
$.ajax({
url: 'your/url/to/the/action',
success: function (data) {
// use data JSON to update page.
// then, call this function again recursively after a timeout of 15 minutes = 900 s = 900,000 ms
setTimeout(refreshDataAndUpdatePage, 900000);
}
}
And of course, call it somewhere.

detect first page load jquery session

Once the user logs in, i am displaying an alert to user based on a check on page load method. Now when the user navigates to other aspx pages and clicks on home again, I don’t want him to see the alert again. I want to achieve this with jquery and session variable. In a way I want to check first page load by jquery using a session variable.
I could do this with Session and RegisterStartupScript
User Login code
public void doLogin(string userName, string pwd)
{
// validate user
// check to see whether need to show alert
Session["ShowAlert"]=true;
Response.Redirect("Home.aspx");
}
in Home.aspx
Option 1
protected void Page_Load(object sender, EventArgs e)
{
if(Session["ShowAlert"]!=null)
{
String scriptName = "PopupScript";
if (!IsClientScriptBlockRegistered(csname1))
{
StringBuilder cstext = new StringBuilder();
cstext.Append("<script type=\"text/javascript\"> function showUserAlert() {");
cstext.Append("alert('message');} ");
cstext.Append("</script>");
RegisterStartupScript(cstext, cstext.ToString());
Session.Remove("ShowAlert");
}
}
}
Option 2:
Just define a javascript variable var in the page and use it in $(function(){...})
protected void Page_Load(object sender, EventArgs e)
{
if(Session["ShowAlert"]!=null)
{
String scriptName = "PopupScript";
if (!IsClientScriptBlockRegistered(csname1))
{
StringBuilder cstext = new StringBuilder();
cstext.Append("<script type=\"text/javascript\">");
cstext.Append("var showAlert=true;");
cstext.Append("</script>");
RegisterClientScriptBlock(cstext, cstext.ToString());
Session.Remove("ShowAlert");
}
}
}
JS
$(document).ready(function(){
if(showAlert)
{
alert('ShowMessage');
}
});
I made this exact feature a couple of weeks ago, but used a mySQL database instead of using sessions. If you are wanting to display the alert to the user only once EVER (or as close to forever as possible) or just once a week etc, then you should use cookies instead of sessions.
Otherwise, you can detect when the page has loaded simply with jQuery:
$().ready(function(){
if(!$.session.get("viewed_page")){
alert("some message");
$.session.set("viewed_page", true);
}
});
No need for session here.
You can use the session cookie itself.
$(function (){
if (document.cookie.indexOf("yourToken")>-1)
{}
else
{
// show the window , and set a cookie
}
});

Rewrite url for video

I am newbie with asp.net. I have a url of video http://localhost/video/file.mp4 , but i want to serve url like http://localhost/34567fghft/file.mp4 to make timeout for url, is there some solution to my question? Sr for my english, im stuct around with this, waiting for your answers, thanks
You can on Global.asax, and on Application_BeginRequest to get the requested path, split it, see if has expired or not, manipulate the string and send him ether to an error page, ether rewrite it to the real path:
protected void Application_BeginRequest(Object sender, EventArgs e)
{
string cTheFile = HttpContext.Current.Request.Path;
if (cTheFile.EndsWith("/file.mp4", StringComparison.InvariantCultureIgnoreCase))
{
// manipulate your string to see if is expired...
string[] keys = HttpContext.Current.Request.Path.Split('/');
// get the 34567fghft part
if (IfExpired(keys[keys.Length - 1]))
{
HttpContext.Current.Response.Redirect("ExpiredMessage.aspx", true);
return ;
}
else
{
HttpContext.Current.RewritePath("http://localhost/video/file.mp4", false);
}
}
}
Please note this code is the idea on how you do it. Is need some better string manipulation and error check.

Calling a non static method in Server Side by a Client Side Function

I can get an object from the server side by using static receive callbackresult methods from server side.
But I want to run a non-static method in my page which populates an ajax accordion by calling a client side function.
The object I am calling from server side is a complex object which I can't use in client side if I get it by callbackresults.
Is there any other solution that I can run a non static method in an aspx file by a client side control ?
Codes I am using so far ...
function ReceiveServerData(arg, context) {
//Message.innerText = "Date from server: " + arg;
}
#region ICallbackEventHandler Members
public void RaiseCallbackEvent(String eventArgument)
{
// Processes a callback event on the server using the event
// argument from the client.
Insert(); // this is running, but doesnt work !
//printAlternativesFromAirport(eventArgument);
}
public string GetCallbackResult()
{
// Returns the results of a callback event to the client.
return null;
}
#endregion
protected void Page_Load(object sender, EventArgs e)
{
ClientScriptManager cm = Page.ClientScript;
String cbReference = cm.GetCallbackEventReference(this, "arg",
"ReceiveServerData", "");
String callbackScript = "function CallServer(arg, context) {" +
cbReference + "; }";
cm.RegisterClientScriptBlock(this.GetType(),
"CallServer", callbackScript, true);
}
yes, you need to create a handler that will create the entire context needed for the page, which will run a full page life cycle ect, and is more recommended when you want to retrieve something like a user control or something big.
public void ProcessRequest(HttpContext context)
{
context.Response.Write(RenderView("~/_controltemplates/15/myDir/Templates/myUC.ascx"));
}
public static string RenderView(string path)
{
try
{
Page pageHolder = new Page();
UserControl viewControl = (UserControl)pageHolder.LoadControl(path);
pageHolder.Controls.Add(viewControl);
StringWriter result = new StringWriter();
Log.Application.Debug(LOGPREFIX + "RenderView before Execute");
HttpContext.Current.Server.Execute(pageHolder, result, true);
return result.ToString();
}
catch (Exception ex)
{
Log.Application.ErrorException(LOGPREFIX, ex);
throw;
}
}
but i think that it is not what you need, instead i would advice you to make an entity (class) to handle that insert function that will not need any httpContext and run it from a simple handler.
another solution you might need, since maybe you do need all the postback info but do not want to make a full postback is to use AjaxPanel or even clear the Response and send "OK" instead.

Asp.net Webform Display Alert and redirect

I'm currently stuck. I have a webform with a button that registers or saves a record.
What i'd like to is have it display a javascript alert and then redirect to a page.
Here is the code i am using
protected void Save(..)
{
// Do save stuff
DisplayAlert("The changes were saved Successfully");
Response.Redirect("Default.aspx");
}
This code just redirects without giving the prompt Saved Successfully.
Here is my DisplayAlert Code
protected virtual void DisplayAlert(string message)
{
ClientScript.RegisterStartupScript(
this.GetType(),
Guid.NewGuid().ToString(),
string.Format("alert('{0}');", message.Replace("'", #"\'").Replace("\n", "\\n").Replace("\r", "\\r")),
true
);
}
Can anyone help me find a solution to this?
Thanks
You can't do a Response.Redirect because your javascript alert will never get displayed. Better to have your javascript code actually do a windows.location.href='default.aspx' to do the redirection after the alert is displayed. Something like this:
protected virtual void DisplayAlert(string message)
{
ClientScript.RegisterStartupScript(
this.GetType(),
Guid.NewGuid().ToString(),
string.Format("alert('{0}');window.location.href = 'default.aspx'",
message.Replace("'", #"\'").Replace("\n", "\\n").Replace("\r", "\\r")),
true);
}
The DisplayAlert method adds the client script to the currently executing page request. When you call Response.Redirect, ASP.NET issues a HTTP 301 redirect to the browser, therefore starting a new page request where the registered client script no longer exists.
Since your code is executing on the server-side, there is no way to display the alert client-side and perform the redirect.
Also, displaying a JavaScript alert box can be confusing to a user's mental workflow, an inline message would be much more preferable. Perhaps you could add the message to the Session and display this on the Default.aspx page request.
protected void Save(..)
{
// Do save stuff
Session["StatusMessage"] = "The changes were saved Successfully";
Response.Redirect("Default.aspx");
}
Then in Default.aspx.cs code behind (or a common base page class so this can happen on any page, or even the master page):
protected void Page_Load(object sender, EventArgs e)
{
if(!string.IsNullOrEmpty((string)Session["StatusMessage"]))
{
string message = (string)Session["StatusMessage"];
// Clear the session variable
Session["StatusMessage"] = null;
// Enable some control to display the message (control is likely on the master page)
Label messageLabel = (Label)FindControl("MessageLabel");
messageLabel.Visible = true;
messageLabel.Text = message;
}
}
The code isn't tested but should point you in the right direction
This works perfect:
string url = "home.aspx";
ClientScript.RegisterStartupScript(this.GetType(), "callfunction", "alert('Saved Sucessfully.');window.location.href = '" + url + "';",true);
protected void Save(..)
{
// Do save stuff
ShowMessageBox();
}
private void ShowMessageBox()
{
string sJavaScript = "<script language=javascript>\n";
sJavaScript += "var agree;\n";
sJavaScript += "agree = confirm('Do you want to continue?.');\n";
sJavaScript += "if(agree)\n";
sJavaScript += "window.location = \"http://google.com\";\n";
sJavaScript += "</script>";
Response.Write(sJavaScript);
}

Resources