asp.net button onclick post to another page - c#

I have a page in .Net that currently does some processing of info when a button is clicked. It posts back, updates some info and then redirects the user onwards.
What I want to do now is for this same button, when it's clicked, the info is updated but instead of a redirect it does a POST to another site. The reason being that this other site needs to read a bunch of data from the form I submit.
So, I know about the PostBackUrl property but that will stop the processing of the data that I need done.
So is there another way for me to be able to somehow combine both a postback that then becomes as POST to another site?
Or alternatively some way for me to be able to do the updates I need and then do a POST?

The suggested solutions all kind-of worked but the only one that actually did exactly what I needed it to was this one:
Link to SO answer
The reason the other answers above didn't work is that I was POSTing to a payment gateway and for whatever reason their system thought there was a problem with various missing fields in all solutions except the one I linked to. No idea why, I don't have access to their systems to know what they were actually doing.
In any case, thanks for all answers but have a look at the linked one if you're running into a similar issue.

if PostBack isn't absolutely needed, you can actually send them in the request query itself.

You can do a POST from codebehind, you can find details in this answer Redirect to another page using Post method from Code behind

If I got your question right I think you will need to get all the form data from Request.Form and make a HttpWebRequest to the other site:
string url = "http://anothersite.com/";
// create post data
StringBuilder postDataBuilder = new StringBuilder();
foreach (var key in this.Request.Form.AllKeys)
{
postDataBuilder.AppendFormat("{0}={1}&", this.Request.Form[key]);
}
string postData = postDataBuilder.ToString();
// create the web request for the POST
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = postData.Length;
// add the post data
using (StreamWriter requestStream = new StreamWriter(webRequest.GetRequestStream()))
{
requestStream.Write(postData);
}
Hope this helps!

Related

Post data from aspx page to mvc page

I am trying to post data from one page (aspx) to another (mvc). The way I am trying to go about it is in the code behind (aspx.cs) but so far the only way I have found to successfully redirect is to use:
Response.Redirect
which I can't use this because it apparently can only use GET (which won't work because the data I am wanting to transfer can potentially have too many characters for GET to handle). The other stipulation is that I can't use a session variable (the person I'm working with refuses to use session data).
I've looked into things like:
var tdd = new TempDataDictionary();
tdd.Add("subject",subject);
and
Context.Items["subject"] = subject;
but I'm not sure how I'd read that data in the other mvc controller Index method.
Use...
var data = //byte[] containing your data to post
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
using (Stream requestStream = request.GetRequestStream())
{
request.ContentLength = data.Length;
requestStream.Write(data, 0, data.Length);
}
This is assuming you want to programmatically POST from the code behind.
Session wouldn't work going from one web app to another. It only works from one page to another in the same site.

redirecting to page from inside iframe

I have just now started coding in .NET framework, so my apologies if this issue happens to be of trivial nature.
What I got now
A main.aspx page with simple layout using three iframes
the middle iframe content needs to be dynamic (first a login.aspx page and after logging entryform.aspx)
Issue #1 :
After logging in login.aspx inside the iframe, redirecting to main.aspx
The solution I found:
ClientScript.RegisterStartupScript(this.GetType(),"scriptid",
"window.parent.location.href='main.aspx'", true);
(http://forums.asp.net/t/1273497.aspx)
Issue #2
After redirecting/logging how do I change the middle iframe content from login.aspx to entryform.aspx?
The silly solution I thought of:
Add '#form' to the url and listen to hashchange event in main.aspx. But then, anyone can get to the form using the url itself.
So, basically how do I find a secure way to tell the main.aspx page that it needs to change it's middle iframe content after the redirecting/logging
Or by any chance there is a request.setAttribute and getAttribute in .NET like in java that I have missed and made things difficult for me?
Passing variables or values across pages and domains wont be issue, you can use post method and cross page posting for that
After finding that the use of iframe isn't exactly the best idea in my case, I took Tieson T's advice and looked into HttpClient to fetch content from other web pages. In my case it will be both from same domain and other domains.
Since I have 4.0v .NET instead of HttpClient I used HttpWebRequest
code
HttpWebRequest request = (HttpWebRequest)WebRequest.Create (http://localhost:1706/WebSite3/test.html);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader reader = new StreamReader(response.GetResponseStream(),encode );
string html= reader.ReadToEnd();
myDiv.innerHtml(html);
References
HttpClient does not exist in .net 4.0: what can I do?
http://msdn.microsoft.com/en-us/library/456dfw4f.aspx
http://forums.asp.net/t/1382935.aspx/1
http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx
http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.aspx
http://msdn.microsoft.com/en-us/library/system.net.http.httpclient.aspx
Wouldn't it be easier to just pass a parameter to Main.aspx? E.g.
ClientScript.RegisterStartupScript(this.GetType(),"scriptid", "window.parent.location.href='main.aspx?LoadEntry=true'", true);
And client-side JavaScript code inside of 'main.aspx' would read that parameter from 'location.search' and if 'LoadEntry=true' is set - would set SRC of middle frame to "entryform.aspx".
Of course inside of "entryform.aspx.cs" you would need to check if correct login really took place (e.g. some Session variable is set) so nobody would be able to simple set URL manually to "main.aspx?LoadEntry=true" to bypass the login.

HttpWebRequest with POST and GET at the same time

I need to redirect a user to http://www.someurl.com?id=2 using a POST method.
Is it possible? If yes, then how?
Right now I have following and it forwards the POST data properly, but it removes the ?id=2:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.someurl.com?id=2");
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.Length;
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(postData);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
Response.Write(reader.ReadToEnd());
}
The reason I need both query string data -> ?id=2 and POST data is because I pass the query string to page in which javascript is going to be handling the query string data and .NET is going to work with data sent via POST method. The POST data that I am passing can be longer than maximum amount of characters that GET method allows, therefore I can't use only GET method... so, what are your suggestions?
More information:
I am writing a routing page, which adds some custom information to query string and then routes all of the data, old and new further to some URL that was provided. This page should be able to redirect to our server as well as to someone's server and it doesn't need to know where it came from or where it goes, it just simply needs to keep the same POST, GET and HEADER information as well as additional information received at this step.
No. There is no fathomable reason to mix POST and GET.
If you need to make parameters passed in with the request available to Javascript, simply POST them to the server, and have the server spit out the relevant information in a hidden field...
<input type="hidden" value="id=2,foo=bar" disabled="disabled" />
Simple as that.
Note: Disable the hidden field to exclude it from the subseqient POST, if there is one ;)
The problem i think that the problem could be that postData does not contain the id parameter as it is supplied through querystring.
Posted data is in the body of the request and querystring data is in the url.
You probably need to fetch the id from request.querystring to you postdata variable.
Given the extra information to your question, that you require to submit to an external source, what I believe you must do is process all of the data and return a form with hidden fields. Add some javascript to submit that form to the external URL immediately upon load. Note that you won't get file uploads this way, but you can appropriately handle POST and GET data.
As far as I know, it isn't possible to redirect with POST. Couldn't you simply pretend (internally handle as if) that the request was made to the page you want to redirect the user to?
The closest answer I've found to this problem is here, but it's not transparent to the user, therefore it's not good enough for me --> Response.Redirect with POST instead of Get?
If anybody has any other suggestions, please respond!
Try sending all of the data including the id in POST. Then when you are processing the data in C#, you can read the id variable in and write it back out to your webpage within a tag:
<script type="text/javascript">
id = <%=request_id%>
</script>
Then just make sure your javascript starts running after fully loaded with an onload() call and you're good to go.
What you are actually trying to do is redirect your POST data. May I ask why? I can't see any reason why you would want to do this if in fact both pages are on your servers.
What you should be doing is processing all of your POST data in script #1, and then redirecting to something like script2.aspx?id=234 where the ID 234 is in reference to the data in your database. You can then recall it later on script2 and dump all the data into Javascript variables for your client-side stuff to use.
Either way, something about this process sounds fishy to me. Mixing up your data processing client-side and server side is like mixing vodka and milk. It rarely works well. (But white russians sure are tasty!)
Actually I was able to achieve the desired result by mixing Javascript and Codebehind code. So, what I've done is in server side code I've built an entire web page like following:
var strForm = new StringBuilder();
strForm.Append("<form id=\"" + formId + "\" name=\"" + formId + "\" action=\"" + url + queryString +"\" method=\"POST\">");
foreach (string key in data)
{
strForm.Append("<input type=\"hidden\" name=\"" + key + "\" value=\"" + data[key].Replace("\"", """) + "\">");
}
strForm.Append("</form>");
And in addition to this form built on server side, I add a javascript code that submits the form I've just built.
var strScript = new StringBuilder();
strScript.Append("<script language='javascript'>");
strScript.Append("var v" + formId + " = document." + formId + ";");
strScript.Append("v" + formId + ".submit();");
strScript.Append("</script>");
strForm.Append("</form>");
So, what this code does, is as you see, the form action is an URL with query string parameters attached to it... but since the form method is POST, we submit the values we added as a hidden fields as POST parameters... So we end up submitting both POST and GET parameters.
Hope this solution will help somebody =)

HTTP Requests in C#

I need to visit a URL, find a specific text box in said page - fill it with data and then submit a form.
How can I accomplish this in C#?
P.S. Innocent intentions.
You'd be best looking at the WebRequest class (System.Net).
You'll want to look at the POST Method to post a form (click the submit button with the required fields completed).
Example:
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create ("http://www.contoso.com/PostAccepter.aspx ");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "This is a test that posts this string to a Web server.";
byte[] byteArray = Encoding.UTF8.GetBytes (postData);
There is a nice tutorial and lots of information on MSDN here. (Continuation of above source code)
if you visit the page in a browser and do the stuff you need manually with fiddler2 installed and activated you can see which requests get sent to the webserver.
All you need to do is to replicate those requests (form posts) using for example the WebRequest class or the WebClient class in the .net framework.
WatiN is also an alternative.

Reading and posting to web pages using C#

I have a project at work the requires me to be able to enter information into a web page, read the next page I get redirected to and then take further action. A simplified real-world example would be something like going to google.com, entering "Coding tricks" as search criteria, and reading the resulting page.
Small coding examples like the ones linked to at http://www.csharp-station.com/HowTo/HttpWebFetch.aspx tell how to read a web page, but not how to interact with it by submitting information into a form and continuing on to the next page.
For the record, I'm not building a malicious and/or spam related product.
So how do I go read web pages that require a few steps of normal browsing to reach first?
You can programmatically create an Http request and retrieve the response:
string uri = "http://www.google.com/search";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
// encode the data to POST:
string postData = "q=searchterm&hl=en";
byte[] encodedData = new ASCIIEncoding().GetBytes(postData);
request.ContentLength = encodedData.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(encodedData, 0, encodedData.Length);
// send the request and get the response
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
// Do something with the response stream. As an example, we'll
// stream the response to the console via a 256 character buffer
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
Char[] buffer = new Char[256];
int count = reader.Read(buffer, 0, 256);
while (count > 0)
{
Console.WriteLine(new String(buffer, 0, count));
count = reader.Read(buffer, 0, 256);
}
} // reader is disposed here
} // response is disposed here
Of course, this code will return an error since Google uses GET, not POST, for search queries.
This method will work if you are dealing with specific web pages, as the URLs and POST data are all basically hard-coded. If you needed something that was a little more dynamic, you'd have to:
Capture the page
Strip out the form
Create a POST string based on the form fields
FWIW, I think something like Perl or Python might be better suited to that sort of task.
edit: x-www-form-urlencoded
You might try Selenium. Record the actions in Firefox using Selenium IDE, save the script in C# format, then play them back using the Selenium RC C# wrapper. As others have mentioned you could also use System.Net.HttpWebRequest or System.Net.WebClient. If this is a desktop application see also System.Windows.Forms.WebBrowser.
Addendum: Similar to Selenium IDE and Selenium RC, which are Java-based, WatiN Test Recorder and WatiN are .NET-based.
What you need to do is keep retrieving and analyzing the html source for each page in the chain. For each page, you need to figure out what the form submission will look like and send a request that will match that to get the next page in the chain.
What I do is build a custom class the wraps System.Net.HttpWebRequest/HttpWebResponse, so retrieving pages is as simple as using System.Net.WebClient. However, my custom class also keeps the same cookie container across requests and makes it a little easier to send post data, customize the user agent, etc.
Depending on how the website works you can either manipulate the url to perform what you want. e.g to search for the word "beatles" you could just open a request to google.com?q=beetles and then just read the results.
Alternatively if the website does not use querystring values (url) to process page actions then you will need to work on a webrequest which posts the required values to the website instead. Search in Google for working with WebRequest and webresponse.

Categories