Friday, June 3, 2011

How to Post data to other sites using iFrame and Post Method

First Add this in Design
-------------------------

<iframe style="display: none" width="0px" height="0px" id="ifrmNewPage" runat="server"></iframe>

using System.Xml;
using System.IO;
using System.Web.Script.Serialization;

public class RemotePost
    {      

        private System.Collections.Specialized.NameValueCollection Inputs = new System.Collections.Specialized.NameValueCollection();


        public string Url = "";
        public string Method = "post";
        public string FormName = "form1";
        public string UserID= "";       

        public void Add(string name, string value)
        {
            Inputs.Add(name, value);
        }       
        public string ConstructPostString()
        {

            StringBuilder strPostString = new StringBuilder();

            strPostString.Append("<html><head>");           

            strPostString.Append(string.Format("</head><body onload=\"document.{0}.submit();\">", "form1"));
            strPostString.Append(string.Format("<form id=\"{0}\" name=\"{0}\" method=\"{1}\" action=\"{2}\" >", "form1", Method, Url));
            for (int i = 0; i < Inputs.Keys.Count; i++)
            {
                strPostString.Append(string.Format("<input name=\"{0}\" type=\"hidden\" value=\"{1}\" />", Inputs.Keys[i], Inputs[Inputs.Keys[i]]));
            }
           
            strPostString.Append(string.Format("<input name=\"{0}\" type=\"hidden\" />", FormName));
            strPostString.Append("</form>");
            strPostString.Append("</body></html>");


            return strPostString.ToString();
        }        
    }

public string WriteText(string strPostString)
    {                           
        string strFileName = Server.MapPath(".\\"FolderName"\\HTML\\" + "FileName" + ".html");

        using (StreamWriter sw = new StreamWriter(strFileName, false, Encoding.ASCII))
        {
            sw.AutoFlush = true;
            TextWriter tw = sw;
            tw.WriteLine(strPostString.ToString());
            tw.Flush();
            tw.Dispose();
            tw.Close();
        }
        return ".\\"FolderName"\\HTML\\" + "FileName" + ".html";
    }



RemotePost myremotepost = new RemotePost();
myremotepost.Url = "Action URL";
myremotepost.FormName = "FormName";
myremotepost.Method = "post";

//myremotepost.Add("FieldName", "value");
myremotepost.Add("Name", "John");
myremotepost.Add("Gender", "Male");

Session["ResponseString"] = myremotepost.ConstructPostString();
string strPath = WriteText(Session["ResponseString"].ToString());

ifrmNewPage.Attributes.Add("src", strPath);

To Remove file after Posting
----------------------------

strFileName = Server.MapPath(".\\"FolderName"\\HTML\\" + "FileName" + ".html");
    if (File.Exists(strFileName))
        File.Delete(strFileName);