Encountered an issue when trying to invoke an Asp.net method from Javascript

Is it possible to call an Asp.Net function from Javascript? I have a code sample that calls an Asp.net MVC function in this way:

@{
    var payUrl = "/recordings/recording-123.wav";

    <!-- saves the wav file to local folder called recordings using a session value to create unique file names -->
}
    function setupRecorder() {
        Wami.setup({
            id: "wami",
            onReady: setupGUI
        });
    }

    function setupGUI() {
        var gui = new Wami.GUI({
            id: "wami",
            recordUrl: "http://localhost:5296/home/Save",
            playUrl: "@payUrl"
        });

        gui.setPlayEnabled(false);
    }

Here is the specific code segment being referenced:

recordUrl: "http://localhost:5296/home/Save",

The HomeController contains a method named Save that is invoked here:

public ActionResult Save()
        {
            Request.SaveAs(Server.MapPath("/recordings/recording-123.wav"), false);
            return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
        }

I am attempting to achieve the same functionality in Asp.Net but struggling to find a solution. If anyone can offer assistance, I would greatly appreciate it as this is a crucial aspect of my project for saving audio data. Here is my attempt:

<script>
    function setupRecorder() {
        Wami.setup({
            id: "wami",
            onReady: setupGUI
        });
    }

    function setupGUI() {
        var gui = new Wami.GUI({
            id: "wami",
            recordUrl: "Default.aspx/Save",
            playUrl: "/recordings/recording-123.wav"
        });

        gui.setPlayEnabled(false);
    }
</script>

I have a webform Default.aspx with a method named save:

recordUrl: "Default.aspx/Save",

This is the implementation of the method in default.aspx.cs. I have tried using [HttpGet] and [HttpPost] tags, but nothing seems to be working for me.

 [HttpGet]
[System.Web.Services.WebMethod]
    public void Save()
        {
            Request.SaveAs(Server.MapPath("/recordings/recording-123.wav"), false);
            return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
        }

Answer №1

Your Save function should be declared as a static method because it is being used as a webmethod. This will allow you to call it from JavaScript.

[System.Web.Services.WebMethod]
public static void Save()
{
    Request.SaveAs(Server.MapPath("/recordings/recording-123.wav"), false);
    return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
}

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

Jquery adds a fun, wobbly effect to animations

I'm experiencing an issue with the animation I've implemented causing some slight shaking and wobbling of the text and certain elements which is affecting the overall look. You can view a live example of this behavior here: This problem specific ...

The methodology of executing a Javascript function

I have the following code snippet: (function() { $(document).ready(function() { //Event handlers $('.project-delete').on('click', function() { deleteProject($(this)); }); $('.keyword-delete').on(&ap ...

Is it required for custom activity/workflow classes in Windows Workflow Foundation to be sealed?

It has come to my attention that the default Visual Studio template for a workflow, as well as most of the code snippets I have come across online, are declared as sealed. How would I go about creating a new activity or workflow based on an existing one ...

Having trouble getting a jQuery variable to work as an argument in an onclick function for an HTML

success: function(jsonresponse) { data = JSON.stringify(jsonresponse); $.each(JSON.parse(data), function (index, item) { var Id=item.id; var JobId=item.JobId; var eachrow = "<tr>" + "<td>" + item.id + "</td>" ...

What is the equivalent of Stopwatch.GetTimestamp() in NodeJS?

Is there a way to achieve the same functionality as Stopwatch.GetTimestamp() in NodeJS? I tried the following approach but got different results: Javascript: (Date.now()*10000)+621355968000000000; //returns 637414085816080000 C# Stopwatch.GetTimestamp() ...

Navigating through the text in between search restrictions of lookbehind and lookahead can be

Below is the text I am working with. Hello my name is Adam (age: 25) I live in US. Hello my name is Bill (age: 23) I live in Asia. I am trying to extract the age and location using lookahead and lookbehind. The desired output format should be as follows ...

The implementation of useProxy in puppeteer does not return a valid function or constructor

Currently, I am using puppeteer and attempting to utilize a proxy per page. To achieve this, I am making use of a package called puppeteer-page-proxy. const puppeteer = require('puppeteer'); var useProxy = require('puppeteer-page-proxy&ap ...

Guide on sending emails with AngularJS and the Ionic framework

I have been attempting to send an email by using various links, but without success. I am looking for guidance on how to successfully send an email. Below is the code I have been using for sending emails. Any suggestions for changes would be greatly apprec ...

Leveraging the FileReader API within a Vue.js component function

I'm working on a Vue.js file picker that needs to display previews of selected files. To accomplish this, I am utilizing the FileReader API to read user-selected files as data URLs using the readAsDataURL method of the FileReader object. However, I&a ...

What is the best way to dynamically change the color of a Vue component button through a function?

Can anyone provide guidance on how to change the button color of a Vue component using a function while utilizing Bootstrap-vue? The code snippet below demonstrates how a tooltip can be altered through a function, but how can this concept be extended to mo ...

What is the best way to display a div based on a keyword match?

If the keyword search results in a match, I can display the corresponding input text and its related category div. Now, I am attempting to also search through category names. If the searched keyword matches a category name, that specific div should be visi ...

Utilize the onClick Event to Trigger Function with an Array in ReactJS

Every time I attempt to pass an array as a value to a function by clicking on a div, I encounter the error below: Uncaught Invariant Violation: Expected onClick listener to be a function, instead got a value of object type. If passing an array to a fun ...

The phonegap-plugin-push does not successfully register

Currently, I am delving into the realm of app development using Phonegap and experimenting with the Phonegap push plugin available here. I am encountering an issue where the register event fails to fire even after initialization. Here are the steps I have ...

Transforming a triangular shape into a square using Plane Geometry in THREE.js

I have an animation created with triangles in the link below. Is there a way to convert these triangular areas into squares? The animation currently has a line running through the middle when using "PlaneGeometry". Removing this line would turn the triangl ...

exploring the contrast of css versus javascript selectors

Could you please explain the contrast between div#name and #name? Is there a significant difference when using class or id to position an element? Thank you for your help. ...

"Prisma vs. Supabase: A Comparison of Image Uploading

I am encountering an issue with adding image URLs to the Prisma database. I have successfully uploaded multiple images from an input file to Supabase storage, but when I try to add their URLs to the database, I receive an error regarding property compatibi ...

Using AJAX and PHP to redirect a PHP page once specific conditions are satisfied

Hello, I am currently facing an issue and I could use some guidance with Ajax as I am still learning how to work with it. The situation is this: I have a webpage that undergoes a refresh every 7 seconds using Ajax and Javascript. During each refresh, one ...

Tips for displaying backend error messages on the frontend

I am facing an issue with returning error messages from the backend to the frontend in my Angular project. The specific requirement is to display an error message when the value of msisdn is not eligible for renewal. Currently, the hardcoded error message ...

Trigger a bootstrap modal using JavaScript within a PHP environment

Upon encountering a failed login attempt, I attempted to open a Bootstrap modal using the code below: if (mysqli_num_rows($query) != 0) { // Login successful } else { // Login failed echo '<script type="text/javascript"> $("#LoginF ...

Ways to verify if a string is a number without using isNaN and with specified criteria

I am trying to determine if a string represents a valid number without relying on the isNaN function. The reason for this is that I need to be able to accept the ',' character, which isNaN ignores. Additionally, I do not want to allow negative nu ...