Search code examples
c#asp.nethttp-postcode-behind

Best way to create and post a form in codebehind in C#


I'm using webforms and I need to create and POST an http form to a payment gateway for one of my clients. I'm using a user control that is displayed in a masterpage, however they already have an existing <form> on the page, so I'm pretty sure I cannot add another.

What is the best practice method to create and post a form in C# from the code behind? Currently I have the following:

var nvc = new System.Collections.Specialized.NameValueCollection
    {
        {"EWAY_ACCESSCODE", ewayResponse.AccessCode},
        {"EWAY_CARDNAME", txtCcName.Text},
        {"EWAY_CARDNUMBER", txtCcNumber.Text},
        {"EWAY_CARDEXPIRYMONTH", ddlCcExpMonth.SelectedValue},
        {"EWAY_CARDEXPIRYYEAR", ddlCcExpYear.SelectedValue},
        {"EWAY_CARDCVN", txtCcv.Text}
    };

    var client = new WebClient();
    client.UploadValues(ewayResponse.FormActionURL, nvc);

This does work, but is there a better / alternative way to do it?


Solution

  • Aside from the previous suggestion:

    • why wouldn't a (simpler) Button.PostbackUrl work?

      <asp:Button ID="externalPost" runat="server" PostBackUrl="http://www.somewhere.com/" Text="Post Somewhere" />
      

    Also, assuming that's a payment gateway you're referring to, you're doing a server-side POST, which has implications on PCI Compliance (vs. a direct form post from client/browser).

    Hth.