Thursday, August 16, 2012

dynamically POST the FORM to third party URL / Site

 We want to POST FORM to third party URL or any other site. But in ASP.Net pages we cant do directly. so below customized function to send FORM dynamically.

private void ResponseToClient()
    {
        try
        {
            NameValueCollection data = new NameValueCollection();
            data.Add("Field1", "val1");
            data.Add("Field2", "val2");
            string ResponseURL = "responsesimulator.aspx";

            string strForm = ConstructInternalFormToPost(ResponseURL, data);
            this.Page.Controls.Add(new LiteralControl(strForm));
        }
        catch (Exception Ex)
        {
           

        }

    }

    private static String ConstructInternalFormToPost(string url, NameValueCollection data)
    {

        string tmpformID = "PostForm";
       
        StringBuilder strConstructForm = new StringBuilder();
        strConstructForm.Append("<form id=\"" + tmpformID + "\" name=\"" +
                       tmpformID + "\" action=\"" + url +
                       "\" method=\"POST\">");

        foreach (string key in data)
        {
            strConstructForm.Append("<input type=\"hidden\" name=\"" + key +
                           "\" value=\"" + data[key] + "\">");
        }

        strConstructForm.Append("</form>");
       
        StringBuilder ConstructScript = new StringBuilder();
        ConstructScript.Append("<script language='javascript'>");
        ConstructScript.Append("var v" + tmpformID + " = document." +
                         tmpformID + ";");
        ConstructScript.Append("v" + tmpformID + ".submit();");
        ConstructScript.Append("</script>");
       
        return strConstructForm.ToString() + ConstructScript.ToString();
    }

No comments:

Post a Comment