问题
What's the purpose of using PostBackUrl
?
Let's say I have a button
which is in Cart.aspx:
<asp:Button ID="btnContinue" runat="server" Text="Continue Shopping" PostBackUrl="~/Order.aspx" CssClass="btn" />
That means that I will be redirectd to Order.aspx, rather than staying on original Cart.aspx. Here are my two questions:
I also have a
TextBox
in Cart.aspx.
When I click thebutton
, the value of theTextBox
will be posted back to Order.aspx rather than original Cart.aspx. Now I think we can only get this value if it is posted back to Cart.aspx, which contains thisTextBox
.
What if I want to retrieve this value on the new page?If there is no way to retrieve any input on Cart.aspx, why do we need to use PostBackUrl? We could just add:
Response.Redirect("~/Order.aspx")
to the Cart.aspx.cs?
回答1:
If you do not specify the entry PostBackUrl
, the button will submit the data back to the same page, in your case it is cart.aspx.
The purpose of PostBackUrl
is a across-page-posting of data.
If you specify PostBackUrl="~/Order.aspx"
, your data will be posted back to your Order.aspx page. In your Order.aspx page, you will be able to get your TextBox
(which was in cart.aspx) data using:
Page.PreviousPage.FindControl("TextBox1")
You can learn more at https://msdn.microsoft.com/en-us/library/ms178139.aspx
回答2:
Base on my understanding (I might be wrong but).
Web pages are stateless. The value of your textbox disappears once you leave/ or perform a postback. If you need the values from this page, use cookies, viewstate, sessions or query string to be able to retrieve this value/s.
You don't need PostBackUrl but if you prefer to use it, its up to you. And yes, Response.Redirect("~/Order.aspx") can be use after you do whatever you need to do in CodeBehind. PostBackUrl is will do the same but will not execute codes that you might need before redirecting.
来源:https://stackoverflow.com/questions/44307483/purpose-of-postbackurl-in-aspbutton