tony horn
tony horn

Reputation: 33

Calling script from Blazor with parameters

I've been given a script function and would like to partially translate it to C# in a Blazor app

<script> 
    function pay() {
                    var token = document.getElementById('token').value;
                    var card = document.getElementById('card').value;
                    var exp = document.getElementById('exp').value;
                    var cvv = document.getElementById('cvv').value;
                   var paymentData = {
                        ssl_txn_auth_token: token,
                        ssl_card_number: card,
                        ssl_exp_date: exp ,
                        ssl_cvv2cvc2: cvv
                    };

                    ConvergeEmbeddedPayment.pay(paymentData);
                    return false;
                }
        </script>

I want to call the script (that is inside the script above)

 ConvergeEmbeddedPayment.pay(paymentData);

Directly from c# . Like so

await JsRuntime.InvokeVoidAsync("ConvergeEmbeddedPayment.pay", paymentData);

There is some good information here:

https://learn.microsoft.com/en-us/aspnet/core/blazor/call-javascript-from-dotnet?view=aspnetcore-3.1
But it stops short of helping me.

What kind of variable should I pass in the paymentData parameter? And how should I pass it? I've tried var , object and string and also tried JsonSerializer.Serialize( ); but no luck Based on suggestion from @BurningKarl I tried Dictionary and object[] but I get an error saying the content is missing or "Expected BEGIN_OBJECT but was STRING "

Upvotes: 3

Views: 6911

Answers (1)

Roman Simuta
Roman Simuta

Reputation: 96

Looks like you have to create your own c# class that mimics the payment data object in your Javascript. Something like this

public class PaymentData
{
    public string ssl_txn_auth_token {get; set;}
    public string ssl_card_number{get; set;}
    public string ssl_exp_date{get; set;}
    public string ssl_cvv2cvc2{get; set;}
}

Then you have to create an instance of this class and pass it to InvokeVoidAsync as an argument.

var data = new PaymentData ()
    {
       ssl_txn_auth_token = "authtokenvalue",// you have to get it from control
       ssl_card_number = "card number",
       ssl_exp_date: "date", // probably it should be daytime or similar
       ssl_cvv2cvc2 = "111"
    }
await JsRuntime.InvokeVoidAsync("ConvergeEmbeddedPayment.pay", data);

Upvotes: 6

Related Questions