Search code examples
c#asp.net-mvc-4razorpayment-gatewayhttp-status-code-400

Redirect with POST parameters in MVC 4 for Payment Gateway Integration


I am trying to do a payment gateway integration using mvc4 in razor. In that i need to call a page with prefilled post form.

Using the below method, I am forming the post method form:

private static string PreparePOSTForm(string url, System.Collections.Hashtable data)      // post form
    {
        //Set a name for the form
        string formID = "PostForm";
        //Build the form using the specified data to be posted.
        StringBuilder strForm = new StringBuilder();
        strForm.Append("<form id=\"" + formID + "\" name=\"" +
                       formID + "\" action=\"" + url +
                       "\" method=\"POST\">");

        foreach (System.Collections.DictionaryEntry key in data)
        {

            strForm.Append("<input type=\"hidden\" name=\"" + key.Key +
                           "\" value=\"" + key.Value + "\">");
        }

        strForm.Append("</form>");
        //Build the JavaScript which will do the Posting operation.
        StringBuilder strScript = new StringBuilder();
        strScript.Append("<script language='javascript'>");
        strScript.Append("var v" + formID + " = document." +
                         formID + ";");
        strScript.Append("v" + formID + ".submit();");
        strScript.Append("</script>");
        //Return the form and the script concatenated.
        //(The order is important, Form then JavaScript)
        return strForm.ToString() + strScript.ToString();
    }

And in my Controller page I am calling the PreparePostForm with required parameter and I am receiving the POST request format.

[HttpPost]
 public ActionResult OrderSummary()
        {
            string request=PreparePOSTForm("payment URL","hashdata required for payment")
            return Redirect(request);
        }

But while redirecting I am getting below error.

Bad Request - Invalid URL

HTTP Error 400. The request URL is invalid.

I am missing something here to work with POST request. Can someone help me.

Thanks in advance.


Solution

  • You cannot post a form by Redirect method. You could send generated form string to View and after that post the form by Javascript.

    public ActionResult OrderSummary()
    {
        string request=PreparePOSTForm("payment URL","hashdata required for payment")
        return View(model:request);
    }
    

    and in View of OrderSummary:

    @model string
    
    @Html.Raw(Model)
    
    <script>
        $(function(){
           $('form').submit();
        })
    </script>