make the POST request from the controller

1

I have the need to make a POST request from the controller before loading the view, I want to do this due to a certain condition that is required of me.

The condition is:

  

If I have more than one product under contract show a "Menu" with the contracted products, otherwise if I only have 1 show the view of that product and not the "Menu".

The code of the Menu controller is:

public ActionResult MenuApps(){
  if (WSKernel.Suscriptions_WebDevices_Get(productosDatos, out productosRespuesta)) {
    model.Productos = productosRespuesta.ListSuscriptions_WebDevices;
    //si solo se cuenta con un solo producto, hacer redireccion directa al unico producto
    if (model.Productos != null && model.Productos.Length == 1){
      switch (model.Productos[0].AdmixProduct){
        case "Producto1":
          return Redirect("http://localhost/Producto1");
        case "Producto2":
          return Redirect("http://localhost/Producto2");
      }
    }
  }else{//sin productos}
}

But doing return Redirect("http://localhost/Producto2"); makes a request HTTP by GET since I want to send information and I want the user not to see it just because I need to always log in correctly.

On the other hand, where I want to redirect is another project that is already finished and this is configured to receive information by POST.

How can I make the POST request and redirect to the page from the controller?

    
asked by JuankGlezz 22.05.2017 в 20:45
source

1 answer

2
  • First of all my idea was to return a script with an AJAX request from Javascript, but I was faced with the problem that I could not redirect to the page, so it was not what I needed.
  • I decided to return a view with a form, but the problem was that the page always appeared blank and towards the request, it was not very well seen either.
  • After several attempts and a lot of research I found this post where he explains the attempts he made, but apparently my second idea was on the right track, only that on the page he does it with a Helper .

    The idea of Helper is simple:
    for each value of the key you want to publish, we create a hidden field, we create the form, then we add the sequence of commands needed to do the automatic sending by calling vPostForm.submit() from the JavaScript code .

    Therefore the code would look like this:

    private static String PreparePOSTForm(string url, NameValueCollection data)
    {
        //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 (string key in data)
        {
            strForm.Append("<input type=\"hidden\" name=\"" + key + 
                           "\" value=\"" + data[key] + "\">");
        }
    
        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();
    }
    

    Now to consume this private method you need the following:

    public static void RedirectAndPOST(Page page, string destinationUrl, NameValueCollection data)
    {
      //Prepare the Posting form
      string strForm = PreparePOSTForm(destinationUrl, data);
      //Add a literal control the specified page holding 
      //the Post Form, this is to submit the Posting form with the request.
      page.Controls.Add(new LiteralControl(strForm));
    }
    

    Well, now in my controller I would use something like this:

    Dictionary<string, object> postData = new Dictionary<string, object>();
    postData.Add("first", "someValueOne");
    postData.Add("second", "someValueTwo");
    return this.RedirectAndPost("http://TheUrlToPostDataTo", postData);
    

    Now, yes, the condition that you had to respect is fulfilled:

      

    If I have more than one product under contract show a "Menu" with the contracted products, otherwise if I only have 1 show the   view of that product and not the "Menu".

    Samer Abu Rabie code and credit

    While you want to do something simpler in MVC there is the Nuget package like Fluentx.Mvc (Recommended) , in which you no longer need to create the helper in a file, you only need to import the package with using Fluentx.Mvc;

    To use it is the same way.

    Dictionary<string, object> postData = new Dictionary<string, object>();
    postData.Add("first", "someValueOne");
    postData.Add("second", "someValueTwo");
    return this.RedirectAndPost("http://TheUrlToPostDataTo", postData);
    
        
    answered by 22.05.2017 / 20:45
    source