Interacting with C# Web Assembly using JavaScript in .NET MVC

I am trying to call a C# code from JavaScript in an MVC .NET application, excluding Blazor. The following code snippet is specific to the .NET and MVC stack, not a generic AJAX query like another one on Stack Overflow. After making the Ajax call, there are no error messages, and it simply proceeds to the next statement. There might be two possible issues that I can identify. Firstly, my URL: '/Home/CreatePostcodeFromCoordinates' could be incorrect. Secondly, maybe my C# assembly is not part of the assembly or something similar. Coming from a database background, I admit I am not very experienced with web technologies, but fixing this shouldn't be too hard, right? I can't seem to find anything else that is wrong. Also, does the return value from the C# code need to be in a special format, or is returning a string (as currently implemented) sufficient?

console.log("just before /Home/CreatePostcodeFromCoordinates");

$.ajax({
    type: "POST",
    url: '/Home/CreatePostcodeFromCoordinates',
    data: { param1: longitude, param2: latitude },
    success: function (response) {
        console.log('success');
        console.log(response);
    },
    error: function (error) { 
        console.error(error);
    }
});

Answer №1

After a long struggle, I finally found the solution:

In my MVC project, I was calling a C# method. I realized that the issue was caused because my C# method was declared as static. Once I removed the static declaration, everything started working smoothly. It took me about 8 hours to figure this out and I wouldn't want anyone else to go through the same frustration. Make sure to include the async:false option in your code to avoid wasting precious time!

C#

public string CreateCoordinatesFromPostcode(string postcode)
{ 
  string result = "XXXXXX" // your logic
  return result;
}

JavaScript

 let result = '';
 $.ajax({
     type: "POST",
     url: '/clib/CreateCoordinatesFromPostcode',
     async: false,
     data: { postcode: postcode },
     success: function (response) {
         result = response;
     },
     error: function (error) {
         console.error(error);
     }
 });

 console.log("just after  /clib/createCoordinatesFromPostcode");

 return 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

Leverage the power of JavaScript by utilizing it as the view

Currently, in my React app, the view engine is set to hbs. There are a few hbs files in the Views folder. The following code snippet is in my app js file: // View engine app.engine( 'hbs', hbs({ extname: 'hbs', }) ) app.set ...

What is the reason behind the error "Unable to load type" in the Resx file?

I am encountering a designer error in my code: The Component for which I want to define a List of properties: using System.Collections.Generic; using System.ComponentModel; using System.Windows.Forms; namespace TestProjectForProperty.Test { public c ...

Prioritizing the execution order of useEffect in Next.js

Here is the code snippet from my _app.tsx useEffect(() => { console.log(1) }, []); And this portion of code is from my index.tsx useEffect(() => { console.log(2) }, []); Currently, in the console it prints 21 However, I want it to print 12 ...

Trouble altering target framework to 4.0 in Visual Studio

I am currently developing a Windows Forms application that does not utilize any new technologies from the .NET Framework version 4.5-4.7. However, I mistakenly started the project with the .NET Framework set to 4.6.2. (Initially, the company specified they ...

Retrieving the most recent records through AJAX in chronological order

Over the past 5 days, I've been exploring different methods to gather new data in order to complete the notifications system. I am determined to finish this task before moving on to something else. Initially, I attempted using local storage but it did ...

Enhance Website Speed by Storing PHP Array on Server?

Is there a way to optimize the page load time by storing a PHP array on the server instead of parsing it from a CSV file every time the page is reloaded? The CSV file only updates once an hour, so constantly processing 100k+ elements for each user seems un ...

C# programming with Selenium WebDriver for Headless Browsing and Unit Testing: A Comprehensive Introduction

After several months of using Selenium Webdriver in C# and gaining proficiency, I have encountered a scenario at work where I need to test the UI of a web-based browser product with multiple users simultaneously. As I have previous experience with jMeter f ...

It appears that the PHP file is not being executed when attempting the second JSON POST request

After successfully retrieving data from the database using jQuery, PHP, and MySQL, I encountered an issue with my second AJAX call. Here is the first part of my code: $( document ).ready(function() { $( '#create-checklist' ).submit(function( ...

svg-import.js encountered an import error stating "Unexpected type sodipodi:namedview in SVG Import."

Currently, I am utilizing svgjs to load SVG files and perform various manipulations. In addition, I have integrated the svg-import plugin to bring in pre-existing SVG files. However, when attempting to load an SVG file, I encountered the following error: ...

Developing a project in Asp.net MVC without utilizing Entity Framework to establish foreign key relationships

My database consists of 2 tables: Posts(ID,Title,DateTime,Body) & Tags(Id,Name), with a relation table PostsTags(PostID,TagID). In addition, there are two C# classes defined: public class PostModel { [Key] [Required] public int ID { get; set; ...

Tips for transferring express route handling to the subsequent middleware and bypassing the current block of code

Here's the current setup of my route handler in my express app: app.use('/', function(res, req, next) => { if (!authorised) next(); f1(); f2(); }); Is there a way to prevent f1() and f2() from running without adding conditional st ...

The Ajax code is not functioning as expected. The first one is not being displayed in the two connected XHR functions

fiddle : http://fiddle.jshell.net/xvwz2bt4/ Using the ajax code below (pure js) : var xhr; xhr = new XMLHttpRequest(); function xhrDocOpen(doc,placeID){ xhr.onreadystatechange=function(){ if(xhr.readyState==4 && xhr.status==200){ ...

Randomly, an AJAX request sent from Internet Explorer 11 to a node.js server operating behind an Apache proxy may abruptly terminate

When using angular on a webpage, a get request is initiated to retrieve json data after a user action. The issue arises when attempting this request on Internet Explorer 11, as it fails randomly while working smoothly on Firefox. Below is a screenshot of t ...

Acquiring JSON data within a JavaScript function using PHP

Requesting assistance on reading a JSON value using the code below, to retrieve data based on the $movieID. <script> function bookBTN(x) { <?php $url = 'http://movie.com/movieOne?seatNum=' . x; $jsonURL = file_get_ ...

Choose a specific <div> element by its unique ID and trigger a click event on it as soon as the page loads

There is a div element on my webpage tagged with the ID of #activateeditbutton. I am hoping to have this specific div trigger a click event upon the page's initial loading. In an attempt to achieve this functionality via jQuery, I have written the fo ...

Why must the form be submitted with 2 clicks?

My form has two submit buttons, but why does it require two clicks to submit the form? Here is how my form looks: <form id="mychkform" method="POST" class=""> <input type="email" class="form-control" id="email" name="email" placeholder="En ...

The scroll-to-top button refuses to fade out

I am currently facing a challenge with my scroll to top button not functioning properly. It seems like there is an issue arising from another animation that I can't seem to pinpoint. Specifically, when the other animation is triggered at "scroll hits ...

Unable to retrieve data from a nested object within a JSON structure

In my React project, I have created a function component like the one below: function FetchData() { const [randomUserData, setRandomUserData] = useState(''); const url = 'https://randomuser.me/api/'; const fetchData = () => { ...

asp.net mvc json response includes newline character

Hello there! I have a question regarding my use of an asp.net MVC controller to interact with a third party REST API. While I am able to successfully retrieve a response from the API, I am encountering an issue with newline characters within the response. ...

Struggling to get PHP json_encode to work with jQuery?

While developing a website on my computer, I had no trouble getting AJAX requests with jQuery to work smoothly. However, when moving the site to the production server, I encountered some issues. This is how the CodeIgniter controller I have handles return ...