C#, HTML, JavaScript, Programming, Web

Write a JavaScript/HTML Form Submit Post From C# APSX Code Behind

There may be a case where you are taking information from a form and need to post it to a web site somewhere else. One quick method of performing that post is to execute it from the code behind using C# (via context.response) and JavaScript. This is a scaled down example of a case where I was submitting a POST from the code behind of a web part control:

A couple things to note:

  • You can add as many fields as you wish to post, I am only using two
  • You can use string.Format to get C# variables to put directly in the POST
protected string value1;
protected string value2;

value1 = "something";
value2 = "something else";

Context.Response.Write("<form name='Form1' id='Form1' method='post' action='https://www.mywebsitetopostto.com/example'>");
Context.Response.Write("<input type='hidden' name='__VIEWSTATE' id='__VIEWSTATE' value='' />");
Context.Response.Write(string.Format("<input type='hidden' name='txtValue1' id='txtValue1' runat='server' value='{0}' />", value1));
Context.Response.Write(string.Format("<input type='hidden' name='txtValue2' id='txtValue2' runat='server' value='{0}' />", value2));
Context.Response.Write("</form>");
Context.Response.Write("document.Form1.submit();");
Context.Response.Flush();
Context.Response.End();

Ideally you would use this in a case where you are posting content and the page you are posting to will process and serve something after the form that receives your post processes what you sent. Please do not use this snippet and blame me for a blank page 🙂

2 thoughts on “Write a JavaScript/HTML Form Submit Post From C# APSX Code Behind”

  1. When I originally commented I clicked the -Notify me when new comments are added- checkbox and now each time a comment is added I get four emails with the same comment. Is there any way you can remove me from that service? Thanks!

    Like

Comments are closed.