How To Post To A Remote Server From An ASP.NET Web Form

I recently came an across an interesting problem: I had to post an ASP.NET Web Form to a third party Web site. It turns out to be quite a tricky thing to do – so I thought I’d share my solution with you in case you ever need to do the same thing.

First off: why did I want to post on rather than back?

I am in the process of taking over responsibility for an existing Web site. The site integrates with a bank to take credit cards – and the data needs to be posted.

So why not just use HttpWebRequest?

Because the user has to leave the site, pay and then come back – bringing return parameters back with them.

Ok – so how did the current site work?

It cheated. It’s an ASP.NET Web Forms site, but the page that does the posting is actually PHP!

So – what exactly is the problem with just switching to an ASP.NET Web Form?

Actually, there are several:

  1. ASP.NET Web Forms post back to the same page (or, at a pinch, to other pages on the same server). They don’t post on to third party web sites.
  2. The remote server requires set names for the posted fields – and ASP.NET Web Forms changes these on the client. This problem had two sub-problems:
    1. I had to use runat=”server” controls because the values were dynamic, and
    2. It turns out that ClientIDMode=”Static” fixes IDs, but not names

Q: So how did I make it work?

A: By using jQuery

Here’s what I did:

  1. Added a label telling the user that they needed JavaScript to pay by credit card (or they could pay by bank instead)
  2. Hid the label using jQuery, then showed a button (input type=”button”, not submit) and set its click event to….
  3. Rewrite the form’s action so that it posted to the remote address
  4. Rewrite the control names so that they met the remote sites requirements.
  5. Remove the unwanted form elements such as __VIEWSTATE
  6. Submit the form

Then all I had to do was test it – which I did by creating a page to echo the newly posted values back to the (which also meant I had to set EnableViewStateMac=”false” on the test page).

Here is the JavaScript:

$(function () {
$(‘#needJavaScript’).hide();
$(‘#buttonSubmit’).show().click(function () {
$form = $(‘form:first’);
$form.attr(‘action’, “test.aspx”);
$(‘#__VIEWSTATE, #__EVENTTARGET, #__EVENTARGUMENT’).remove();
$(‘input:hidden’).each(function () {
var original = $(this).attr(‘name’);
var improved = original.substring(original.lastIndexOf(“$”) + 1, original.length);
$(this).attr(‘name’, improved);
});
$form.submit();
});
});

So there you have it – a way to post to a remote server from an ASP.NET Web Forms Web site.

Kevin Rattan

For other related information, check out these courses from Learning Tree:

Building Web Applications with ASP.NET and Ajax

jQuery: A Comprehensive Hands-On Introduction

Type to search blog.learningtree.com

Do you mean "" ?

Sorry, no results were found for your query.

Please check your spelling and try your search again.