I am interested to know what specifically Page.IsPostBack means. I am fully aware of it's day to day use in a standard ASP.NET page, that it indicates that the user is
submitting data back to the server side. See Page:IsPostBack Property
But given this HTML
<html>
<body>
<form method="post" action="default.aspx">
<input type="submit" value="submit" />
</form>
</body>
</html>
When clicking on the Submit button, the pages Page_Load method is invoked, but the Page.IsPostBack is returning false. I don't want to add runat=server.
How do I tell the difference between the pages first load, and a Request caused by the client hitting submit?
update
I've added in <input type="text" value="aa" name="ctrl" id="ctrl" /> so the Request.Form has an element, and Request.HTTPMethod is POST, but IsPostBack is still false?
Check the Request.Form collection to see if it is non-empty. Only a POST will have data in the Request.Form collection. Of course, if there is no form data then the request is indistinguishable from a GET.
As to the question in your title, IsPostBack is set to true when the request is a POST from a server-side form control. Making your form client-side only, defeats this.
One way to do this is to extend the ASP.NET Page class, "override" the IsPostBack property and let all your pages derive from the extended page.
public class MyPage : Page
{
public new bool IsPostBack
{
get
{
return
Request.Form.Keys.Count > 0 &&
Request.RequestType.Equals("POST", StringComparison.OrdinalIgnoreCase);
}
}
}
In the example that you include in your question, there is no viewstate involved; there is no way for the server to link this request to a previous request of the page and treat them as a unit. The request resulting in clicking the button will look like any other random request coming in to the server.
Generally a you could view a PostBack as a combination of:
HTTP request method equals "POST"
HTTP header HTTP_REFERER equals the current URL
That's not 100% foolproof tho, it does not take into account any state of any kind (which you probably want even if you don't know it) but it is a post, back to the current page.
You could check the headers to see if your input controls are returning a value (using Request.Forms as tvanfosson points out). However, the really big question is why you would not want to add runat=server. The entire page processing edifice implemented by ASP.NET (except MVC) depends on processing the page output through the server to set up the appropriate client-side code for callbacks, etc.
Related
Can a GET request cause IsPostBAck to be true ?
I never tried it but I read that it (somewhere) that it can be done If I add _ViewState , _EventValidation and form params.
It it true ? Can this cause a PostBack ?
Thanks.
edit
I found it here
here
edit 2 after testing - it does WORKING
I didnt't find even one topic about this in the web.
here it is :
http://imageshack.us/f/688/croppercapture1q.gif/
I make a new answer after the update of the question. Actually I make a working example, and I confirm the question, that is can be done !
http://www.planethost.gr/SOPostBackTest.rar
What I do:
I make an aspx page, render it, then get and make an html with the render page, and just change the method from post to get
<form name="form1" method="get" action="PostBackTest.aspx" id="form1">
then I open the html page, and make a get to the aspx page ! and the aspx page is actually see it as IsPostBack.
The results is surprise me. The Flag IsPostBack is set to TRUE, you can see and test it by your self. I do not know how to consider this - BUG, or feature that asp.net work so good that what ever you send them on the form is make it work.
And yes the Request.HttpMethod can show more accurate if is GET or POST command.
I have a generic 'form page' user control that we use that allows editors to insert whatever kind of html form they want to inside of it, and it handles all of the form posts.
My question is, is there a way to store the vanilla non-asp form entries in the viewstate or otherwise save the entries on a form post, in the case that some server-side validation fails, so they can be restored when the page refreshes?
We currently already do upfront javascript validation that catches the majority of the input errors. We store all the form post data in a db before we do further processing, and some of the entries contain junk (spam we wish to ignore) or only partial info (i'm assuming those are cases where the user doesn't have javascript enabled). I'm trying to catch these last fringe cases so we do not process them.
If I am understanding this correctly,
1>User fills form
2>Clicks submit
3>Error detected on the server side
4>The Html posted back should contain the form i already filled with an error message on top.
Have you considered using JQuery Ajax?
The jquery ajax will post to a web method. The web method returns a JSON response. If the response is success redirect user to the next page, else show error on top of the page.
That way you don't need to maintain the state of the user input (since it is never lost).
If you dont know what the form fields are ahead of time then I would reccomend that you look into partial postbacks.
Or else post the forms via ajax.
you could store the text HTML in
<asp:HiddenField ID="hid1" runat="server" />
this will be passed in View State
I am creating a callback page that receives info from a payment gateway and then updates a database. I then want it to 'submit' itself automatically to a 'thank you' page, passing the order number as a hidden field.
I have looked at httpwebrequest, but I can't see with this solution how it will 'post itself' if that's the right way to put it.
Any help on ho to achieve this would be greatly appreciated.
If the callback page is regular ASP.NET you could do a server-side Response.Redirect or Server.Execute.
If not you can do a client-side post in javascript:
<form action="yourThankYouUrl.aspx">
<input type="hidden" name="callbackValue" value="yourCallbackValue" />
</form>
<script type="text/javascript">
document.forms[0].submit();
</script>
So, why not using that receive page to also show what you need and save the trouble to have one more page?
If you still want to have a 2nd page just to show the result, at the end of the processing you can write:
Session["job-id"] = "12345679";
Response.Redirect("my2ndpage.aspx");
in that 2nd Page, you simply assign the session text to the control you will have
HiddenField1.Value = Session["job-id"].ToString();
Sorry, another super basic ASP.NET question. this so embarrassing.
I am reading the article on How to: Pass values between ASP.NET pages
In the second approach, they suggest hooking up a button and directing the user to another page using POST. I don't know how to do this. How do I HTTP POST?
"When the source page uses the HTTP POST action to navigate to the target page, you can retrieve posted values from the Form collection in the target page."
This is how I am sending the user to the new page:
protected void btnSubmitForPost_Click(object sender, EventArgs e)
{
Response.Redirect("GetViaPost.aspx");
}
EDIT
The final solution:
You can use ASP.NET webforms. Do the following: On the first page, create your controls and a button that sends the user to a new page. Handle the click event from this button. As stated below, use Server.Transfer with endResponse=false, instead of Response.Redirect(). When you use Response.Redirect, your post data is cleared out. I did not need to specify action in the form or anything else.
In ASP.NET when you click a button, you're posting the entire page's fields by default (as it's contained within a gigantic <form /> tag last time I checked. You can access these values after clicking the button like this:
string MyPostedValue = Request.Form["MyFormField"];
*Edit as per your update in your question, change Response.Redirect() to Server.Transfer() like this:
protected void btnSubmitForPost_Click(object sender, EventArgs e)
{
Server.Transfer("GetViaPost.aspx", true);
}
Then in your GetViaPost.aspx's page you can get any form/query string variable you passed from your sending page like this:
string MyPostedValue = Request.Form["MyFormField"];
If I'm reading this right, all of these answers are missing the question...
You're looking at posting from one Asp.Net form to another, and one of the methods is what you want to figure out - doing a normal http post. The book or article probably is already telling you about the Server.Transfer as another option if I'm guessing right.
If I'm getting the question right, then the simplest answer is to not use a standard ASP.Net form (with the runat = server attribute) as the starting point, but to use a simple standard html form to post to an asp.net page
<form action = "targetpage.aspx" method="post">
...some form fields here
<input type = "submit">
</form>
If in the codebehind you wire up to the button click event, then click the button. It's a POSTback that happens.
Any controls that you have runat="server" will be accessible by their id (and any values set on them) in the codebehind.
In terms of posting data to other pages, you have a number of options available to you.
The querystring, sessions, cookies and viewstate.
A basic example (with no error handling) given your updated Response.Redirect might be:
int someId = int.Parse(txtBoxOnThePage.Text);
Response.Redirect(string.Format("GetViaPost.aspx?myId={0}", someId));
Then on the GetViaPost page you could pull that out by:
HttpContext.Current.Request.QueryString["myId"]
http://www.asp.net/learn/ is a surprisingly good source of information and tutorials for this kind of learning.
ASP.NET buttons always perform a POST. You can set which page the button posts to using the PostBackUrl property of the button. If you leave this blank, the button will post back to the same page that is resides on.
Check out this article for more information.
If I see something like:
if(Request["Email"])
{
}
What does this actually mean? Where is the Email collection member actually being set?
It's retrieving the variable from get/post parameters.
somepage.aspx?blah=1
string blahValue = Request["blah"];
Console.WriteLine(blahValue);
> 1
Even more specificially:
Cookies, Form, QueryString or ServerVariables
http://msdn.microsoft.com/en-us/library/system.web.httprequest_members(VS.71).aspx
See this for example.
Taken from the above link
All variables can be accessed directly by calling Request(variable) without the collection name. In this case, the Web server searches the collections in the following order:
QueryString
Form
Cookies
ClientCertificate
ServerVariables
It retrieves either the submited form values (POST) or the submitted querystring values (GET).
You would generally see it written as either Request.Form["Email"] or Request.Querystring[Email"] instead of just Request["Email"].
Example of Form (POST) method:
On the HTML or ASPX Page:
<form action="SomePage.aspx">
<input type="hidden" name="Email" value="someaddress#email.com" />
<input type="Submit" value="Submit Form" />
</form>
Once the form has been submitted by clicking the Submit Form button you would retrieve the form values using Request.Form["Email"] (or just Request["Email"] for the lazy :))
Just some additions to the posts of the others.
To have things more explicitly you normally use Request.QueryString[...] for getting values from the QueryString, so when a GET request has been done and Request.Form[...] when a POST request is done. Although in the latter case you usually directly access the values of your server controls, since ASP.net uses the ViewState mechanism to load back on your controls when the request comes back from the client.