Invoking a C# function from JavaScript

I need to implement a way to invoke the method GetAccount from my controller AccountController.cs within my JavaScript factory LoginFactory.js. Here is an example of what I am trying to achieve:

AccountController.cs:

public Account GetAccount(string userName)
    { ... }

LoginFactory.js:

if(x>y) {
   var account = <%AccountController.GetAccount(someParam);%>
}

I have attempted using [WebMethod] and Ajax, however, I have been unable to make it work as I keep receiving a 404 error response.

Answer №1

Supposing that your RetrieveAccount function is accessible at /User/RetrieveAccount while your program is functioning, you can utilize the following approach:

$.ajax({
  type: 'GET',
  url: '/User/RetrieveAccount',
  data: { 'username' : 'a-username' },
  dataType: 'json',
  success: function(jsonData) {
    alert(jsonData);
  },
  error: function() {
    alert('error');
  }
});

Please note that this method relies on jQuery.

This prompts the browser to send a request to /User/RetrieveAccount just as if you had manually entered the URL in the address bar, but it retrieves and processes the returned JSON data for use in your client-side (JavaScript) code.

If a 404 error occurs, it would be prudent to verify your routing configuration.

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

"The challenge of achieving a transparent background with a PointMaterial texture in ThreeJS

When creating a set of particles with THREE.Points and using a THREE.PointMaterial with texture, I noticed that the transparency of the particles is working only partially. The textures are stroke rectangles created with canvas. Here is what my particles ...

Tips for resolving the issue of "Unable to assign property '_DT_CellIndex' to undefined in Jquery Datatable"

<?php if(mysqli_num_rows($result)>0) {?> <table class="table table-striped" id="example" align="center"> <tr> <thead> <th style=&quo ...

Looking for the time trigger feature in jQuery using typeahead search?

Is there a way to trigger an event every 3 seconds in Laravel Vue.js? I am currently using jQuery in my script. The issue is that when I type something in the search input field, the event is triggered after each character I type. What I want is for the ev ...

Having trouble with Django's submit POST method for creating objects

Latest Updates: I have successfully implemented a feature where the page does not reload upon clicking the submit button. To achieve this, I filled out the form and inspected the page source code. The form structure was as follows: https://i.sstatic.net/ ...

utilizing async/await without the need for babel-polyfill

Here is the code I am working with: @action async login(payload){ try { this.loginLoading = true const data = await request('/admin/login', { method: 'post', data: payload }) this.logined = ...

"Utilizing Rails with the power of Ajax and Jquery to enhance the Post

Currently, I am facing an issue with an AJAX post data call in my Rails project. The data is successfully entering the database, however, the SUCCESS function is not functioning as expected. When trying to execute an alert within the success function, it d ...

Executing a function a specific number of times in Jquery

I have a query regarding JQuery related to randomly placing divs on a webpage. The issue I'm facing is that it currently does this indefinitely. Is there a way to make it run for a specific duration and then stop? $(document).ready(function () { ...

Change the database utilized by ASP WEB API 2

Currently, I have an ASP WEB API 2 application that is built using Entity Framework 6 code-first approach. My goal is to create Selenium tests for this application utilizing a test database generated through migrations. The reason behind the need for a te ...

Exploring Material UI choices and retrieving the selected option's value

Could someone help me with this issue? When I console.log target, the output is as follows: <li tabindex="-1" role="option" id="mui-21183-option-0" data-option-index="0" aria-disabled="false" aria-select ...

Using Stored Procedures versus ADO.NET in C# Applications: Which is the Better Choice?

Currently working on a C# Application that utilizes SQL Server for data storage. While I find it convenient to make data changes programmatically at times, I also see the benefits of having stored procedures and functions in the database. As a beginner i ...

Container for Magazines using HTML and CSS

Looking to develop a digital magazine application with smooth swipe transitions and fade in effects when swiping left and right. I attempted using jQuery.mobile, but struggled with adapting the background image height. My goal is to create a universal web ...

Every time I try to launch NPM start, an error pops up on my screen

Whenever I try to execute the command: npm start An error message pops up saying: npm ERR! missing script: start This is what my package.json file looks like: { "name": "react-app", "version": "0.1.0", "private": true, "dependencies": { " ...

Loading a specific CSS file along with an HTML document

Creating a responsive website, I'm looking to incorporate a feature that allows for switching between a mobile version and a standard desktop version similar to what Wikipedia does. To achieve this, I would need to reload the current HTML file but en ...

Provide a numerical representation of how frequently one object value is found within another object value

Account Object Example in the Accounts Array: const accounts = [ { id: "5f446f2ecfaf0310387c9603", picture: "https://api.adorable.io/avatars/75/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e6b7d7a666 ...

Error encountered when downgrading a component from Angular v5 or v4 to AngularJS due to an injector issue

I have successfully created a basic angular5 component called HelloComponent: var HelloComponent = function () { }; HelloComponent.annotations = [ new ng.core.Component({ selector: 'hello-world', template: 'Hello World!' } ...

What is the process to transfer data from JavaScript to HTML within a Laravel environment?

I am attempting to transfer a value from JavaScript to HTML as a variable. In order to do this, I am retrieving the value from a Laravel PHP controller. JavaScript $("ul.nav-tabs > li > a").click(function() { var id = $(this).attr("href").repla ...

Tips for saving/downloading generated QR codes in React Native

Using this code allows me to generate QR Codes, but I am struggling with saving the generated QR Code in PNG or JPEG format. I have tried a few examples without success and I am continuing to try different methods. import React, { Component } from 'r ...

My code in .NET consistently triggers a URI mismatch error 400 as it continually redirects to an incorrect URL

Any help is appreciated right now. I'm currently attempting to connect to the Google Drive API using OAuth2, but I keep encountering an error when I run my credentials: credential = GoogleWebAuthorizationBroker.AuthorizeAsync( ...

Integrating Python Script with User Input and Output within a JavaScript Web Application

I have an existing JS website that requires additional functionality, and after some research I believe Python is the best tool to handle the necessary calculations. My goal is for users to input information that will then be used as input for my Python ...

What is the best way to retrieve the date and time using the Open Weather API for a specific city

Currently, I am in the process of developing a weather application using React and integrating the Open Weather API. Additionally, I have incorporated an external library for weather icons. The functionality allows users to input a city name and receive t ...