Getting an error when trying to call a C# method from JavaScript

Recently, I have been attempting to execute a C# method from JavaScript within my ASP.NET page named parameters.aspx. However, each time I hit the button to trigger the method, an error 404 is displayed.

Let's take a look at the C# method defined in parameters.aspx.cs:

[WebMethod]
public void MethodSearch()
{
   // Searching for relevant information
   string _sEnrollmentEsiid;
   string _sEnrollmentAddress;
   string _sEnrollmentCity;
   string _sEnrollmentZipCode;

   GetDistributionPointsRequest disRequest = new GetDistributionPointsRequest();
   _sEnrollmentEsiid = disRequest.EsiID;
   _sEnrollmentAddress = disRequest.Address;
   _sEnrollmentCity = disRequest.City;
   _sEnrollmentZipCode = disRequest.Zip;
}

Next, here is the corresponding JavaScript function:

<script type="text/javascript">
function testFunction() {
    $.ajax({
        type: "POST",
        url: 'http://localhost:63788/parameters.aspx/MethodSearch',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            $("#divResult").html("success");
        },
        error: function (e) {
            $("#divResult").html("Something Went Wrong.");
        }
    });
}
</script> 

Lastly, this is how I am calling the function in HTML:

<a href class="btn btn-danger" onclick="testFunction()">Test</a>
<label id="divResult"></label>

I am struggling to pinpoint what exactly is causing the issue. The error message being returned is:

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

Answer №1

If you want to call a [WebMethod] on your page, make sure the method is marked as static. It's important for functions like search to have a return value, so ensure that your method includes this as well. The absence of static may be the specific issue causing problems in your code. If there are other issues present, we can address them once your method is callable.

[WebMethod]
public static void MethodSearch()
{


    //Perform Search
    string _sEnrollmentEsiid;
    string _sEnrollmentAddress;
    string _sEnrollmentCity;
    string _sEnrollmentZipCode;
    //string _sAMS;


    //_sEsiidText
    GetDistributionPointsRequest disRequest = new GetDistributionPointsRequest();
    _sEnrollmentEsiid = disRequest.EsiID;
    _sEnrollmentAddress = disRequest.Address;
    _sEnrollmentCity = disRequest.City;
    _sEnrollmentZipCode = disRequest.Zip;


}

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

Ensure that when adjusting the height of a div, the content is always pushed down without affecting the overall layout of the page

My webpage contains a div element positioned in the middle of the content, with its height being adjustable through JavaScript code. I am seeking a way to manage the scrolling behavior when the height of the div changes. Specifically, I want the content t ...

Is it possible to send an array value from JavaScript Ajax to PHP and then successfully retrieve and read it?

As a newcomer to PHP, I am facing a challenge in saving multiple values that increase dynamically. I'm passing an array value using the following method from my JavaScript code. $(".dyimei").each(function(i,value){ if($(this).val()=="") ...

Adjusting font sizes in JavaScript causes the text to resize

Within my HTML pages, I am adjusting the font size using JavaScript code like this: "document.body.style.fontSize = 100/50/20" However, whenever the font size changes, the text content on the page moves up or down accordingly. This can be disorienting for ...

Show information from database in a drop-down menu utilizing jQuery

tbl_fruits id | name | 1 | banna | 2 | apple | 3 | orange | 4 | kiwi | Currently, I have an HTML script that includes a form for adding users: <form id="form-add_users" autocomplete="off"> &l ...

How can material-ui useScrollTrigger be utilized in combination with a child's target ref?

Attempting to utilize material-ui's useScrollTrigger with a different target other than window presents a challenge. The code snippet below illustrates an attempt to achieve this: export default props => { let contentRef = React.createRef(); ...

Utilizing the jQuery UI Date Picker in an AJAX Request

I have a PHP script that generates HTML along with javascript (specifically the DatePicker from jQuery UI). The PHP script is invoked from a main page using jQuery/AJAX. Although all my HTML is displayed correctly, I encounter a console error that reads: ...

Using Python and Selenium for login, encountering difficulty in locating the div element

# _*_coding:utf-8_*_ from selenium import webdriver driver=webdriver.Chrome() url="https://login.alibaba.com" driver.get(url) driver.implicitly_wait(3) print(driver.page_source) driver.quit() Attempting to use Selenium for logging in, but unable to locat ...

Using Google Chart Tools to pass an array filled with data

My current project involves creating a chart with Google Chart Tools. google.load("visualization", "1", {packages:["corechart"]}); google.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(); d ...

Once you exit the input field, a function activates to alter the background color of the input

Is there a way to trigger a function that changes the background color of an input field when the cursor leaves it? I tried implementing this solution, but it didn't work as expected. <!DOCTYPE html> <html> <body> Enter your name: & ...

Calculating the total price of items in a shopping cart by multiplying them with the quantity in Vue.js

I am currently working on enhancing the cart system in Vue.js, with a focus on displaying the total sum of product prices calculated by multiplying the price with the quantity. In my previous experience working with PHP, I achieved this calculation using ...

Updating the "title" attribute dynamically using jQuery in real time

I have a span that displays data in a tooltip every second, fetched from the server: <span class="info tooltip" title="{dynamic content}"></span> To show the tooltip, I'm using the tooltipsy plugin: $('.tooltip').tooltipsy({ ...

Using jQuery to remove all inline styles except for a specific one

Just a quick inquiry: Our Content Management System (CMS) utilizes CKEditor for clients to modify their websites. The front-end styles include the use of a pre tag, which we have customized to our desired appearance. However, when their team members copy a ...

Using Node.js for a game loop provides a more accurate alternative to setInterval

In my current setup, I have a multiplayer game that utilizes sockets for asynchronous data transfer. The game features a game loop that should tick every 500ms to handle player updates such as position and appearance. var self = this; this.gameLoop = se ...

What is it about the setTimeout function that allows it to not block other

Why is setTimeout considered non-blocking even though it is synchronous? And on which thread does it run if not the main thread? ...

Applying styled text to a Node.js chat application

I developed a chat application using node.js which allows users to enter a username and send messages. The messages are displayed in a <ul> format showing "username: message". I was looking for a way to make the username appear bold and in blue color ...

How can you target the current component and use createElement within VueJS?

My goal is to gain access to the current component and generate a div within it once the component is ready. The following is the code snippet for my component, which demonstrates my attempt to target the this element and create a new div within it using ...

Extracting a specific substring using Regex in C#

Looking for a solution to catch full substring from a string? @"($\w+)" The pattern will successfully detect $substring inside long text $substring the rest of the text. However, it may fail in scenarios like some string $sub.string the r ...

What is the best way to switch between three different menus and ensure that the last selected menu remains open when navigating to a new page

My knowledge of javascript, jquery, and php is pretty much non-existent, unfortunately. I only have a grasp on html and css at the moment. However, I will be starting school to learn these languages in the fall! The issue I am currently facing is creating ...

Failure to establish object reference in web service

Currently, I am dealing with an older asmx web service on a particular server. On this server, I have a consuming app that references the web service and can view all available methods. Additionally, if I visit the web service's URI, I see a standard ...

Converting Milliseconds to a Date using JavaScript

I have been facing a challenge with converting milliseconds data into date format. Despite trying various methods, I found that the solution provided in this link only works for a limited range of milliseconds values and fails for higher values. My goal is ...