locked
Send the value from httppost to view before Javascript RRS feed

  • Question

  • User-1322569703 posted

    That's how I'm building the Stripe SCA 3D. Where I feel right now for it all seems that when in my Httppost Controller gets thrown over to the view where after that javascript scripts can take that data and work on it.

    Im here in terms of strip description.

    [HttpPost]
        [Route("Members/AddMembership/{id}/{CompaniesId}")]
        public async Task<IActionResult> AddMembership(MembersView model)
        {
            try
            {
                ....... more here.......
                //Here before that comes some strip code and everything else ...
                model.PiinVoice = subscription.LatestInvoice.PaymentIntent.ClientSecret;
    
                ....... more here.......
                return View(model);
            }
            catch(Exception e)
            {
                TempData[TempDataClass.Error] = true;
                TempData[TempDataClass.ErrorMsg] = HelperText.ExceptionError + e.Message;
                return RedirectToAction("", "User");
            }
        }

    Javascript here:

        // Create a Stripe client.
        var stripe = Stripe('xxxx');
    // Create an instance of Elements.
    var elements = stripe.elements();
    
    
    
    // Custom styling can be passed to options when creating an Element.
    // (Note that this demo uses a wider set of styles than the guide below.)
    var style = {
      base: {
        color: '#32325d',
        fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
        fontSmoothing: 'antialiased',
        fontSize: '16px',
        '::placeholder': {
          color: '#aab7c4'
        }
      },
      invalid: {
        color: '#fa755a',
        iconColor: '#fa755a'
      }
    };
    
    // Create an instance of the card Element.
    var card = elements.create('card', {
            hidePostalCode: true,
            style: style
        });
    
    // Add an instance of the card Element into the `card-element` <div>.
    card.mount('#card-element');
    
    // Handle real-time validation errors from the card Element.
    card.addEventListener('change', function(event) {
      var displayError = document.getElementById('card-errors');
      if (event.error) {
        displayError.textContent = event.error.message;
      } else {
        displayError.textContent = '';
      }
    });
    
    //I need value here to.
    var paymentIntentSecret = document.getElementById('PiinVoice').value; 
    
    // Handle form submission.
    var form = document.getElementById('payment-form');
        form.addEventListener('submit', function (event) {   
        event.preventDefault();
           
        stripe.handleCardPayment(paymentIntentSecret).then(function(result) {
          if (result.error) {
            // Display error.message in your UI.
              // Inform the user if there was an error.
              var errorElement = document.getElementById('card-errors');
              errorElement.textContent = result.error.message;
          } else {
            // The payment has succeeded. Display a success message.
              stripeTokenHandler(result.token);
          }
        });
    
      //stripe.createToken(card).then(function(result) {
      //  if (result.error) {
      //    // Inform the user if there was an error.
      //    var errorElement = document.getElementById('card-errors');
      //    errorElement.textContent = result.error.message;
      //  } else {
      //    // Send the token to your server.
      //    stripeTokenHandler(result.token);
      //  }
      //});
    });
    
    
    
    // Submit the form with the token ID.
    function stripeTokenHandler(token) {
      // Insert the token ID into the form so it gets submitted to the server
      var form = document.getElementById('payment-form');
      var hiddenInput = document.createElement('input');
      hiddenInput.setAttribute('type', 'hidden');
      hiddenInput.setAttribute('name', 'Source');
      hiddenInput.setAttribute('value', token.id);
      form.appendChild(hiddenInput);
    
      // Submit the form
      form.submit();
    }

    Where the problem lies is that when I click submit then httppost should run first and not the javascript file. I want to hear if it's possible to do that? And at the same time when it's done my subscription.LatestInvoice.PaymentIntent.ClientSecret comes into view so javascript can use it and work on it.

    Wednesday, August 7, 2019 10:51 PM

Answers

  • User1520731567 posted

    Hi Jesper Petersen,

    Do you mean you want to run httppost action after clicking submit button and receive response by ajax?

    If so,I suggest you could use onclick event and ajax when clicking submit button,for example:

     <script>
            $("submitBotton").click(function (event) {
                $.ajax({
                    url: '/Members/AddMembership/1/1',//jump to httppost action,meet [Route("Members/AddMembership/{id}/{CompaniesId}")]
                    dataType: "json",
                    data: ...
                    type: "Post",
                    success: function (result) {//receive response from httppost action
                         //result is the response of the httppost action,you can handle it
                        alert("success");
                    },
                    error: function (xhr) {
                        alert("error");
                    }
                });
    
            });
        </script>

    and modify the result of the httppost action:

    [HttpPost]
        [Route("Members/AddMembership/{id}/{CompaniesId}")]
        public async Task<IActionResult> AddMembership(MembersView model)
        {
            try
            {
                ....... more here.......
                //Here before that comes some strip code and everything else ...
                model.PiinVoice = subscription.LatestInvoice.PaymentIntent.ClientSecret;
    
                ....... more here.......
               // return View(model);
    return Json(model, JsonRequestBehavior.AllowGet);
    } catch(Exception e) { TempData[TempDataClass.Error] = true; TempData[TempDataClass.ErrorMsg] = HelperText.ExceptionError + e.Message; //return RedirectToAction("", "User");
    return Json(e.Message, JsonRequestBehavior.AllowGet);
    } }

    Best Regards.

    Yuki Tao

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 8, 2019 9:16 AM
  • User1520731567 posted

    Hi Jesper Petersen,

    return Json(model, JsonRequestBehavior.AllowGet);

    i can not finde "JsonRequestBehavior.AllowGet" but i how "add" this?

    but i work with .net core 2.2

    In mvc,you just invoke using System.Web.Mvc;,it will work,I suggest you could move to ASP.NET Core to get more help.

    My error now this is:

    Value cannot be null.
    Parameter name: input ERROR

    this error come with here

    console.log(paymentIntentSecret + ' ERROR');

    What is your response in your httppost action?

    Please try to 

    console.log(paymentIntentSecret.PiinVoice);

    Best Regards.

    Yuki Tao

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, August 13, 2019 7:29 AM
  • User1520731567 posted

    Hi Jesper Petersen,

    return Json(model, JsonRequestBehavior.AllowGet);

    Error: The type or namespace name 'Mvc' does not exist in the namespace 'System.Web' (are you missing an assembly reference?)

    Error 2: The name 'JsonRequestBehavior' does not exist in the current context

    I'm sorry that I don't know much about .CORE.

    But I google related information and find that JsonRequestBehavior has been deprecated in ASP.NET Core 1.0.

    So you just use return Json();,like:

    return Json(model);
    

    Best Regards.

    Yuki Tao

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, August 14, 2019 8:02 AM

All replies

  • User1520731567 posted

    Hi Jesper Petersen,

    Do you mean you want to run httppost action after clicking submit button and receive response by ajax?

    If so,I suggest you could use onclick event and ajax when clicking submit button,for example:

     <script>
            $("submitBotton").click(function (event) {
                $.ajax({
                    url: '/Members/AddMembership/1/1',//jump to httppost action,meet [Route("Members/AddMembership/{id}/{CompaniesId}")]
                    dataType: "json",
                    data: ...
                    type: "Post",
                    success: function (result) {//receive response from httppost action
                         //result is the response of the httppost action,you can handle it
                        alert("success");
                    },
                    error: function (xhr) {
                        alert("error");
                    }
                });
    
            });
        </script>

    and modify the result of the httppost action:

    [HttpPost]
        [Route("Members/AddMembership/{id}/{CompaniesId}")]
        public async Task<IActionResult> AddMembership(MembersView model)
        {
            try
            {
                ....... more here.......
                //Here before that comes some strip code and everything else ...
                model.PiinVoice = subscription.LatestInvoice.PaymentIntent.ClientSecret;
    
                ....... more here.......
               // return View(model);
    return Json(model, JsonRequestBehavior.AllowGet);
    } catch(Exception e) { TempData[TempDataClass.Error] = true; TempData[TempDataClass.ErrorMsg] = HelperText.ExceptionError + e.Message; //return RedirectToAction("", "User");
    return Json(e.Message, JsonRequestBehavior.AllowGet);
    } }

    Best Regards.

    Yuki Tao

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 8, 2019 9:16 AM
  • User-1322569703 posted

    You say:

    return Json(model, JsonRequestBehavior.AllowGet);

    i can not finde "JsonRequestBehavior.AllowGet" but i how "add" this?

    So I think it will be best and smart in a way that only PiinVoice will be sent back if it goes well by mail.

    var form = document.getElementById('payment-form');
        form.addEventListener('submit', function (event) {
            event.preventDefault();
            const Id = document.getElementById("PricVat").value;
            const CompaniesId = document.getElementById("CompaniesId").value;
            console.log(Id, CompaniesId); //2 39 - Good!!
            
            $.ajax({
                    url: '/Members/AddMembership/' + Id + '/' + CompaniesId, //jump to httppost action,meet [Route("Members/AddMembership/{id}/{CompaniesId}")]
                    dataType: "json",
                    data: .., //What do I need to do here ??
                    type: "Post",
                    contentType: 'application/json',
                    success: function (result) {//receive response from httppost action
                        //result is the response of the httppost action,you can handle it
                        console.log(Id, CompaniesId);
                        //var paymentIntentSecret = document.getElementById('PiinVoice').value;
                        //console.log(paymentIntentSecret);
                        //var paymentIntentSecret = document.getElementById('PiinVoice').value;
                        //stripe.handleCardPayment(paymentIntentSecret).then(function (result) {
                        //    if (result.error) {
                        //        // Display error.message in your UI.
                        //        // Inform the user if there was an error.
                        //        var errorElement = document.getElementById('card-errors');
                        //        errorElement.textContent = result.error.message;
                        //    } else {
                        //        // The payment has succeeded. Display a success message.
                        //        stripeTokenHandler(result.token);
                        //    }
                        //});
                        alert("success");
                    },
                    error: function (xhr) {
                        alert("error");
                    }
                });
            
            //stripe.handleCardPayment(paymentIntentSecret).then(function (result) {
            //    if (result.error) {
            //        // Display error.message in your UI.
            //        // Inform the user if there was an error.
            //        var errorElement = document.getElementById('card-errors');
            //        errorElement.textContent = result.error.message;
            //    } else {
            //        // The payment has succeeded. Display a success message.
            //        stripeTokenHandler(result.token);
            //    }
            //});
    
            //stripe.createToken(card).then(function(result) {
            //  if (result.error) {
            //    // Inform the user if there was an error.
            //    var errorElement = document.getElementById('card-errors');
            //    errorElement.textContent = result.error.message;
            //  } else {
            //    // Send the token to your server.
            //    stripeTokenHandler(result.token);
            //  }
            //});
        });

    Friday, August 9, 2019 6:55 PM
  • User-1322569703 posted

    but i work with .net core 2.2

    Friday, August 9, 2019 9:26 PM
  • User-1322569703 posted

    My error now this is:

    Value cannot be null.
    Parameter name: input ERROR

    this error come with here

    console.log(paymentIntentSecret + ' ERROR');

    all my code here: 

    $.ajax({
                    url: '/Members/AddMembership/' + Id + '/' + CompaniesId, //jump to httppost action,meet [Route("Members/AddMembership/{id}/{CompaniesId}")]
                    dataType: "json",
                    data: "", //What do I need to do here ??
                    type: "Post",
                    contentType: 'application/json',
                    success: function (result) {//receive response from httppost action
                        //result is the response of the httppost action,you can handle it
                        console.log("New: " + Id, CompaniesId);
                        var paymentIntentSecret = result;
                        console.log(paymentIntentSecret + ' ERROR');
                        //var paymentIntentSecret = document.getElementById('PiinVoice').value;
                        //stripe.handleCardPayment(paymentIntentSecret).then(function (result) {
                        //    if (result.error) {
                        //        // Display error.message in your UI.
                        //        // Inform the user if there was an error.
                        //        var errorElement = document.getElementById('card-errors');
                        //        errorElement.textContent = result.error.message;
                        //    } else {
                        //        // The payment has succeeded. Display a success message.
                        //        stripeTokenHandler(result.token);
                        //    }
                        //});
                    },
                    error: function (xhr) {
                        console.log(xhr)
                    }
                });

    Controller here return:

    model.PiinVoice = subscription.LatestInvoice.PaymentIntent.ClientSecret;
    return Json(model.PiinVoice);

    Friday, August 9, 2019 10:21 PM
  • User1520731567 posted

    Hi Jesper Petersen,

    return Json(model, JsonRequestBehavior.AllowGet);

    i can not finde "JsonRequestBehavior.AllowGet" but i how "add" this?

    but i work with .net core 2.2

    In mvc,you just invoke using System.Web.Mvc;,it will work,I suggest you could move to ASP.NET Core to get more help.

    My error now this is:

    Value cannot be null.
    Parameter name: input ERROR

    this error come with here

    console.log(paymentIntentSecret + ' ERROR');

    What is your response in your httppost action?

    Please try to 

    console.log(paymentIntentSecret.PiinVoice);

    Best Regards.

    Yuki Tao

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, August 13, 2019 7:29 AM
  • User-1322569703 posted
    return Json(model, JsonRequestBehavior.AllowGet);

    Error: The type or namespace name 'Mvc' does not exist in the namespace 'System.Web' (are you missing an assembly reference?)

    Error 2: The name 'JsonRequestBehavior' does not exist in the current context

    For example, if I do this.

    $.ajax({
                url: '/Members/AddMembership/' + Id + '/' + CompaniesId, //jump to httppost action,meet [Route("Members/AddMembership/{id}/{CompaniesId}")]
                dataType: "json",
                data: "",
                type: "Post",
                contentType: 'application/json',
                success: function (result) {//receive response from httppost action
                    //result is the response of the httppost action,you can handle it
                    console.log("New: " + Id, CompaniesId);
                    console.log(result.PiinVoice)
                    //var paymentIntentSecret = document.getElementById('PiinVoice').value;
                    //stripe.handleCardPayment(paymentIntentSecret).then(function (result) {
                    //    if (result.error) {
                    //        // Display error.message in your UI.
                    //        // Inform the user if there was an error.
                    //        var errorElement = document.getElementById('card-errors');
                    //        errorElement.textContent = result.error.message;
                    //    } else {
                    //        // The payment has succeeded. Display a success message.
                    //        stripeTokenHandler(result.token);
                    //    }
                    //});
                },
                error: function (xhr) {
                    console.log(xhr)
                }
            });
    console.log(result.PiinVoice) = undefined

    Unfortunately, it gives me an undefined. But then I also return my json like this. And fix it with using System.Web.Mvc unfortunately it does not work. It will not accept it after.

    Tuesday, August 13, 2019 9:34 PM
  • User1520731567 posted

    Hi Jesper Petersen,

    return Json(model, JsonRequestBehavior.AllowGet);

    Error: The type or namespace name 'Mvc' does not exist in the namespace 'System.Web' (are you missing an assembly reference?)

    Error 2: The name 'JsonRequestBehavior' does not exist in the current context

    I'm sorry that I don't know much about .CORE.

    But I google related information and find that JsonRequestBehavior has been deprecated in ASP.NET Core 1.0.

    So you just use return Json();,like:

    return Json(model);
    

    Best Regards.

    Yuki Tao

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, August 14, 2019 8:02 AM
  • User-1322569703 posted

    Its okay.

    I keep getting this error when it is Value cannot be null. Parameter name: input

    image here to debug:

    Wednesday, August 14, 2019 4:13 PM
  • User-1322569703 posted

    Now i get this... BUT new error: Object reference not set to an instance of an object.

    model.PiinVoice = subscription.LatestInvoice.PaymentIntent.ClientSecret;
    return Json(model);

    js here

    $.ajax({
                url: '/Members/AddMembership/' + Id + '/' + CompaniesId, //jump to httppost action,meet [Route("Members/AddMembership/{id}/{CompaniesId}")]
                dataType: "json",
                data: "",
                type: "Post",
                contentType: 'application/json',
                success: function (result) {//receive response from httppost action
                    //result is the response of the httppost action,you can handle it
                    console.log("New: " + Id, CompaniesId);
                    console.log(result) // HERE ERROR - Object reference not set to an instance of an object.
                    //var paymentIntentSecret = document.getElementById('PiinVoice').value;
                    //stripe.handleCardPayment(paymentIntentSecret).then(function (result) {
                    //    if (result.error) {
                    //        // Display error.message in your UI.
                    //        // Inform the user if there was an error.
                    //        var errorElement = document.getElementById('card-errors');
                    //        errorElement.textContent = result.error.message;
                    //    } else {
                    //        // The payment has succeeded. Display a success message.
                    //        stripeTokenHandler(result.token);
                    //    }
                    //});
                },
                error: function (xhr) {
                    console.log(xhr)
                }
            });

    Wednesday, August 14, 2019 6:15 PM
  • User-1322569703 posted

    i have complete this and thanks for help!!

    Friday, August 16, 2019 10:50 PM