Blazor JavaScript interop encountering difficulty sending parameters to C# function

I'm encountering an issue where I cannot pass arguments to a C# method from JS in Blazor.

Here is the code snippet causing the problem:

<button class="m-2 btn btn-secondary" @onclick="FindMultiplication">Show Sum</button>
public async Task FindMultiplication()
{
    await JSRuntime.InvokeVoidAsync("CallCalculateMultiplication", DotNetObjectReference.Create(this), 1, 2);
}

[JSInvokable]
public int CalculateMultiplication(int no1, int no2)
{
    int multiplication = no1 * no2;
    return multiplication;
}

JS:

function CallCalculateMultiplication(obj, no1, no2) 
{
    var valueR = obj.invokeMethodAsync("CalculateMultiplication", no1, no2);
}

The issue arises when the CalculateMultiplication method of the Blazor Component is not being called.

I have observed that if no arguments are passed to the CalculateMultiplication method, it gets called. The modified code below functions correctly:

[JSInvokable]
public int CalculateMultiplication()
{
    //int multiplication = no1 * no2;
    return 2;
}

function CallCalculateMultiplication(obj, no1, no2) 
{
    var valueR = obj.invokeMethodAsync("CalculateMultiplication");
}

Why is this happening? This used to work in Blazor 3.1 as shown in this YouTube Video (check after 10:00 mark), but now it does not. My question is how should I send arguments to instantiate a razor component C# method?

Answer №1

After some investigation, I discovered that in order to properly execute a C# method from JavaScript, the argument values must be parsed as integers. Below is the revised code for the JS function:

function InvokeCalculateMultiplication(object, number1, number2) 
{
    var resultValue = object.invokeMethodAsync("CalculateMultiplication", parseInt(number1), parseInt(number2));
    resultValue.then(function (result) {
            // Display the result of the promise
            alert(result.toString());
        });
}

Additionally, it is important to handle the result as a JavaScript promise. Here's how it should be managed:

resultValue.then(function (result) {
    // Display the result of the promise
    alert(result);
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Considering a Servlet for managing AJAX requests?

Looking for advice on best practices for implementing a yes or no question with AJAX requests. Open to feedback if I make any missteps along the way. I have a specific Servlet (AjaxServlet?) designated to handle all AJAX requests AjaxServlet is mapped t ...

Is it possible that the use of excessive React.Fragment could impact performance negatively?

After a recent review of our company's code, I discovered that the performance is not up to par. One common pattern I noticed in the code is something like this: condition ? <SomeComponent /> : <></> I see that Fragments are being u ...

Experience the magic of a customized cursor that disappears with a simple mouse movement in your website,

I have been experimenting with designing a custom cursor for my website. After finding a design I liked, I made some adjustments to suit my needs. However, an issue I encountered is that when I scroll, the custom cursor also moves away from its original po ...

Deliver Information to ASP.NET API Using Xamarin

Using C# asp.net, I am delving into the world of creating my very first Xamarin app. I have made changes to my asp.net API to incorporate the following syntax: private SqlConnection con; private SqlCommand com; private void connection() { ...

Adding event listener to a dynamically created video element

Could you provide any insight as to why I'm encountering an error message "Can't create event listener on null" when using the following code: var my; my.newVidObj = document.createElement('video'); my.newVidObj.src = "vid- ...

Stop modal from closing in the presence of an error

My approach involves using a generic method where, upon adding a food item, a modal window with a form opens for the user to input their details. However, since backend validation for duplicate items can only be retrieved after the API call completes. I w ...

What is the process for incorporating items from Slick Grid into a Multi Select TextBox?

Exploring the world of Slick Grid for the first time. Here is where I define my variables in JavaScript. var grid; var printPlugin; var dataView; var data = []; var selectdItems = []; var columns = [ { id: "Id", name: "Id", field: "Id", sortable: t ...

Ensure that my program is halted until the xmlhttprequest has completed

It seems like I've overcomplicated this problem for myself. In my page, I have 2 XMLHTTPRequests - the first request retrieves data from an API and fills my elements with this data. However, one of the fields in my elements requires a second request t ...

How to insert a new document into a MongoDB collection with Mongoose

Consider a scenario where my existing collection called fruits is structured as follows: {"_id" : ObjectId("xyz...."), "name" : "Apple", "rating" : 7} {"_id" : ObjectId("abc...."), " ...

Issue with Repeated String Test in JavaScript: Single Failure Detected

Currently tackling the Repeated String Challenge on HackerRank. The challenge description goes as follows: A string, denoted by s, consisting of lowercase English letters is repeated infinitely. With an integer, n, the goal is to determine and output the ...

Examining the appearance of react-hot-toast using jest testing

As I work on my application, I am facing a challenge in writing a test for the appearance of a react-hot-toast. Whenever a specific button is clicked, this toast pops up on the screen and disappears after a brief moment. Despite being visible both on the s ...

Error: The function row.child.hasClass is not a recognized function

My challenge is creating row details for DataTables without using Ajax. I have implemented something like this: $(document).ready(function () { function format ( name, value ) { return '<div>Name: ' + name + '<br /> ...

jsTree unable to locate node using the provided ID

Implementing the jsTree on the webpage is not a problem for me. I have experimented with numerous suggestions from different sources. $('#myTree').jstree({ .... }) .on('loaded.jstree', function (e, dta) { var t = $('#myTree&a ...

Transforming arrays into nested objects using JavaScript

My array consists of objects structured like this: var exampleArray = [{ name: 'name1', subname: 'subname1', symbolname: 'symbol1' }, { name: 'name1', subname: 'subname11', symbolname: 'sy ...

The valueChanges event of a Reactive Form is activated whenever options from a datalist are selected

Whenever a user types into the input field, I am making an API call to retrieve and display data in a datalist for autocompletion (typeahead). control.get('city').valueChanges.pipe( map((searchText) => searchText.trim().toLowerCase()), fi ...

Dealing with errors and fetching them within a react application using the useState hook

As a newcomer to React, I am currently working with a backend API in my project. One issue I encountered involves the "Login Page" functionality. When a user enters an incorrect username or password and submits the form, the API responds with a message sta ...

Change Coordinated Universal Time (UTC) or Greenwich Mean Time (GMT)

We are currently developing a C# application to function as a client for a web service, specifically designed to run on Windows XP computers. Within the data returned by the web service, there is a DateTime field. The server provides this field in GMT for ...

Deactivate an element completely, preventing any interaction with it, including disabling links that trigger other JavaScript functions

<li class=" active"> <input class="check-shopby" type="checkbox" onclick="$(this).next().click()" checked="checked"> <a class="checked" href="http://mysite/~dev433/products//cooking/cook-tops.html" onclick="$(this).previous().checked = f ...

Exclusive to Safari: Codesandbox is experiencing difficulties retrieving data from the localhost server

Would you mind helping me out with this technical issue I'm facing? For the server/API, I am using this link. As for the mock website, it can be found at this URL. The problem is that, in my code, I'm using axios to fetch data from the locally h ...

What is the best way to implement sorting in a table using react virtualized?

I've been working on implementing sorting in my project using the table sorting demo available on Github. Here is the code I'm using: import React from 'react'; import PropTypes from 'prop-types'; import { Table, Column, Sor ...