How do I HTTP POST from an ASP.NET button? - c#

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.

Related

Postbackurl Vs Response.Redirect (losing data)

I have a button in my aspx page, which in code behind the value of postbackurl gets set. I updated the code to add click event handler and added Response.Redirect code to redirect user to the page once the button is clicked. The only reason i ended up adding click event was because i had to add some extra logic when the button was clicked including redirecting to same url, that was used in postbackurl. The page does get redirected on click however it seems like all the hidden fields from the field gets lost once the form get redirected to the url.
Is there anyway i can submit the form without loosing the hidden data.?
Maybe one way you can solve this problem is to use the server side Transfer() call.
http://msdn.microsoft.com/en-us/library/540y83hx(v=vs.85).aspx
In most cases I've seen what you really want to do is pass the information for the new page using URL parameters. Take all the stuff the new page needs and put it into the url (encrypt if it is security sensitive).
If the only issue you are having is when you want to stay on the same page, this is simple, just have the click event handler return without doing a response.redirect or a transfer.
Post the code if this is not working for you.

Submit a form from code behind

I'm having trouble implementing a functionality on my c#/asp.net app.
I have a form with a RadioButtonList and a submit button.
The RadioButtonList is generated on Page_Load() from a list of objects I retrieve from the database.
I would like to automatically submit the form if there is only 1 object in the list.
I have access to my Form object, to the submit button etc... but I can't seem to find a solution (in the end I'm looking for a kind of form.Submit() ) method.
Does anyone have an idea of how I could do this ?
Thanks in advance !
EDIT >> Here is the code :
.aspx : http://pastebin.com/0E6T7dqH
.aspx.cs : http://pastebin.com/54payZJP
EDIT2 >>>
As it seems there is no way to do what I wanted to do at first, I ended up using a session variable with a response.redirect()
Source :
http://dotnetslackers.com/Community/blogs/haissam/archive/2007/11/26/ways-to-pass-data-between-webforms.aspx
Post happens in the client side. As in Page_Load you are currently executing in the server side, just call the code you want to execute on post.
Edit: For actually going to another aspx
public void Page_Load(object sender, EventArgs e) {
if(!IsPostback && OnlyOneItem) {
Server.Transfer("TheOtherPage.aspx");
}
}
Server.Transfer will maintain the entire request, so your post data will be available.
http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.transfer.aspx
Try something like this
In your Page_Load
if(!IsPostBack)
{
if(check for only one object)
{
//your submit code
}
}
I actually had to do something similar, once. Here is a way you can do it.
Asp.Net buttons have a property called PostBackUrl, and it does exactly what you would expect - it controls where the form will post if you click the button.
You can also use the RegisterStartupScript function to render javascript on the page.
Now, with these two pieces, you can achieve your goal.
if(!IsPostBack)
{
if(results == 1)
{
button.PostBackUrl = "next page's url"
//Register script to click the button using RegisterStartupScript
}
}
Now, having shown you this, I will warn you it may not make for the best user experience. When I did it, it was for a very specific case that had no other solution. The page will actually post back to the user, and they will see the page for a moment before the javascript to click the button takes effect. Additionally, when you set a button's PostBackUrl, that means that when it is clicked, your entire form will be posted to the page specified. The code behind for the current page will not fire at all, so if you have any validation, it won't run.
There's nothing wrong with letting the user click the button to submit the form even if they only have one choice. In my experience, users like to feel like they are in control on the system; they don't like it when pages just do things without their input.
Also, there is not really anything wrong with putting the information the next page needs into the session or even a database table, and using Response.Redirect. It's a fairly common practice and works reliably in most scenarios.

<form> action when using Server.Transfer()

I am using Server.Transfer() to transfer processing from one page to another. The problem is that the form action in the source of the page, having been transferred, refers to the destination page and not the original page as per the URL in the browser.
Is there a way to make the action of the form reflect the URL in the browser, rather than the actual destination page?
Thanks in advance!
Mark
Not to worry, I've rewritten my routing code using the System.Web.Routing namespace so all the logic is centralised in my global.asax. Works a treat!
Thanks for your help.
Mark
if you give the form an id you might be able to change the action in the attributes property.
<form runat="server" id="form1" action="">
</form>
and then in the code refer to the form like this:
form1.Attributes["action"] = "new action";
changing the action will probably cause postback events intended for the new page to work incorrectly. Your other alternative if your design permits would be to use the Response.Redirect.
Also, you might want to look into PostBackUrl for the buttons on the new page, which will change the page that they post to.
You should investigate if HttpContext.RewritePath might be useful here. Typically in cases like this you would use rewrite path on the PreRender event of the destination page using the URL of the original page. This causes controls that use the current internal path to generate URLs and such to "think" they are still on the original URL at the time they render themselves.

URL and Query management Asp.Net C#

Ok so while back I asked question Beginner ASP.net question handling url link
I wanted to handle case like this www.blah.com/blah.aspx?day=12&flow=true
I got my answer string r_flag = Request.QueryString["day"];
Then what I did is placed a code in Page_Load()
that basically takes these parameters and if they are not NULL, meaning that they were part of URL.
I filter results based on these parameters.
It works GREAT, happy times.... Except it does not work anymore once you try to go to the link using some other filter.
I have drop down box that allows you to select filters.
I have a button that once clicked should update these selections.
The problem is that Page_Load is called prior to Button_Clicked function and therefore I stay on the same page.
Any ideas how to handle this case.
Once again in case above was confusing.
So I can control behavior of my website by using URL, which I parse in Page_Load()
and using controls that are on the page.
If there is no query in URL it works great (controls) if there is it overrides controls.
Essentially I am trying to find a way how to ignore parsing of url when requests comes from clicking Generate button on the page.
Maybe you can put your querystring parsing code into IsPostBack control if Generate button is the control that only postbacks at your page.
if (!IsPostBack)
{
string r_flag = Request.QueryString["day"];
}
As an alternative way, at client side you can set a hidden field whenever user clicks the Generate button, then you can get it's value to determine if the user clicked the Generate button and then put your logic there.

Passing master page form data to another webform

I have a master page with one form on it. It is a search form which must always be visible. When the button of that form is clicked I want the form data to be sent to search.aspx. The problem is, I don't know how. I cannot set the form action to search.aspx, because all my other pages which use the master form will go to search.aspx. This I don't want.
Hope someone can help me out :)
Thnx.
In order to pass the values of the control "txtSearch", when Server.Transfer is executed, you could do many things, including passing it via a querystring variable or setting up a session variable, and then check either of those in the Page_Load event of Search.aspx, and if it's populated, call the event that is fired when the user would hit the submit button on the Search.aspx page.
Also, if the Search.aspx file is using the same masterpage, then you can use this.Master.FindControl("txtSearch") to get the control (it you look a the source of the file after it is generated in the browser, you'll notice that controls in the master page aren't really called by their ID, rather that have something appended to them (i.e. it would now possibly be called "ctl00_txtSearch")
You could create your search form in a separate form, and get it to use GET instead of POST.
Either that, or have the master form handle the search button click and use Server.Transfer to go to the search form.
You can have multiple forms in one page I believe. So one form (your search form) would have its action set to search.aspx and the other would be set for the page itself.
ASP.NET webform pages only have one form (which would generally be included on the master page). You can set the postback url for the search button to your search page..
<asp:Button ID="btnSearch" runat="server" Text="Search" PostBackUrl="~/search.aspx" />
..or just redirect to it from the handler in your master page like this:
protected void btnSearch_Click(object sender, EventArgs e)
{
Response.Redirect(#"~/search.aspx?q=" + Server.UrlEncode(txtSearch.Text));
}
..or use Server.Transfer as suggested by David Kemp.
Note: If you use Request.Query[#"q"] on your search page to get your query, you don't need to use Server.UrlDecode() - it's done for you.
I would:
Add some code to the master page code-behind to detect the source of the POST.
Once I have the source of the POST (e.g. the Search box). I would then pass its query to the Search form.
I used a similar process with having a HTML login form on the master page.
I posted a question and subsequent solution here - check it out:
Form Elements in ASP.NET Master Pages and Content Pages
Once I got my head round it, it seemed a pretty simple and reasonably elegant solution.
The benefit of this is that you have complete control over how the data is sent to the search form. And you don't need to enable transfer of form data to the search form and all that nasty stuff, just create a new GET request to the search page and let it do what it is supposed to do :)
Hope this helps.
NOTE:
You can only have one form with runat="server" on an ASPX page. Additional forms MUST be HTML FORMS.
Because your search form is in the master page, you can probably structure it to contain 2 forms. Place the search form tags with the action set to "search.aspx" outside of the tag that is used by the rest of the site.
<body>
<form action="search.aspx>
<!--search box and submit button-->
</form>
<form runat="server">
<!--rest of page inc placeholder-->
</form>
</body>
If the structure of the page will not enable this, you can set the submit button's PosbackUrl to point to "search.aspx". In this case, "search.aspx" would need to be coded to look in the PreviousPage property for the form data, or use Request.Form to access the input.

Categories

Resources