How to invoke a class in JavaScript within Visual Studio

I have a controller class that retrieves data from the database and returns it within a function. I now need to call this function in JavaScript and store the data in variables for display on a page:

Here is an example of my code: exampleController.cs

namespace iSee.WebApiHse.Controllers
{
    public class expController : StandardController
    {

        public expController(
            first myService,
            ISystemSettings systemSettings,
            IService myExpService)
        {
            _myService = MyService;
            _systemSettings = systemSettings;
            _myExpService = myExpService;
        }

        // GET data
        public ActionResult Myexample(int id)
        {
            var elementIds = _systemSettings.ExpIds; 

            var myElements = CacheService.AllVisibleElements
                                  .Where(x => elementIds.Contains(x.Id)).ToList();

            var container = _kpiContainerService.Find(id);

            var result = _myService.MonthByContainer(myElements, container);
            return AsJson(result);
        }
    }
}

The above code successfully retrieves the data. Now, I have a script file named myExp.js where I intend to use this data. How can I achieve this?

Thank you.

Answer №1

In order to retrieve and send computed information from the server, it is necessary to perform a $ajax(..) request using jQuery syntax to your controller.

To achieve this, ensure that the controller method you intend to utilize is accessible for HTTP requests.

For more in-depth information, visit:

How to call controller method from javascript

Answer №2

If you're considering manipulating your controller in the View using JavaScript, think again. It's not a recommended approach. Instead, pass the Model to the View and work with it directly, or utilize ajax to retrieve json-data.

Answer №3

Here is an illustration that utilizes jQuery-ajax to invoke your C# function:

// javascript

var num = 123;

$.ajax({
    url : '/expController/Myexample/',
    type : 'GET',
    data { num : num },
    dataType : 'json', // <-- instruct jQuery to automatically decode the JSON
    success : function(response){
        console.log(response);
    }
});

This script will call your function, providing the num variable as input, and then decipher the JSON into the response object.

To learn about plain Javascript ajax (without jQuery) refer to MDN Ajax.

Answer №4

To initiate the Action Myexample, you must send a request. This can typically be achieved using AJAX:

In your view, consider including:

function triggerAJaxRequest(idToSend) {
    $.ajax({
        url: '@Url.Action("exp", "Myexample")',
        data: { id : idToSend },
        type: "POST",
        success: function(data) {
           $("#HTMLElement").val(data.YourData);
        }
    });
}

If the AJAX call is successful, the response will be stored in the data variable. I have included an example to demonstrate how you can modify the value of an HTML element with the ID HTMLElement.

To execute the function, simply use:

 triggerAjaxRequest(100);

Answer №5

To incorporate the JSON data, store it in a variable and then send it to the designated function in expjs.js. Here is an example:

var jsonData = retrieveDataFromAJAX();
executeJSFunction(jsonData);

The function retrieveDataFromAJAX() is responsible for fetching JSON data from your controller and action.

This should serve as a guide rather than a direct copy-and-paste solution

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

Using AJAX to send both the complete form data and additional data not included in the form

When it comes to passing the entire form to AJAX, I've got that covered. data: $(this).serialize() But what I'm struggling with is how to pass both the form and values outside of the form. For example: var id = $('[name="formid"]'). ...

Run Selenium Grid in a mode where the browser is visible

Currently, I have code set up to run tests in headless mode. However, I am looking for a way to disable headless mode and instead run the tests in an actual browser for debugging purposes. public static void InitBrowser(BrowserEnum browserName) { ...

Is it possible to mimic the functionality of dragging and dropping windows using code?

Although I may have asked a similar question before, I'm still struggling... I need to automate the process of "importing" specific media files into a third-party application (Dartfish) that is closed-source. Here's the situation: All video fi ...

What could be causing the error "styled is not defined as a function" while creating my component library using Rollup?

Currently, I am facing an issue with my component library which is built using React, styled-components, framer-motion, Rollup, and Storybook. The library is being consumed by a NextJS website, but when trying to use it, I keep encountering the following e ...

Exploring the Syntax of JavaScript Objects

<!DOCTYPE html> <html> <body> <p>Creating a JavaScript Object.</p> <p id="demo"></p> <script> var person = { firstName : "John", "las ...

Retrieve data from a JSON string using string manipulation techniques

What is the best way to extract the values of "key" and "key1" from the following string? The data appears to be in JSON format, but parsing it seems to result in an error due to its large size. I am interested in retrieving the values of somelongnumber a ...

Asynchronously load an AngularJS controller from AJAX without altering the route

I am looking to dynamically load an Angular controller after making an AJAX call that generates a new view in HTML. Here is the setup I currently have: Example of a View: HTML Snippet From AJAX <!-- CVS Pharmacy Extracare - Add View --> <d ...

When I press the single quote, the submit button becomes disabled and stops working

image: https://i.sstatic.net/nKCTk.jpg result: https://i.sstatic.net/PE4oN.jpg When I press the '(single quote) key on my keyboard, the submit button (reply button) is not being disabled as expected. I simply want it to be disabled in order to pre ...

Creating a script within a newly generated division element

function addNewChild() { if (childCount <= 2) { childCount++; var newDiv = document.createElement('div'); newDiv.innerHTML = '<br> Prescription '+childCount+':<br><input id="uploadFile" class="disabl ...

Whenever I press the view button, all the cards open instead of just the one I chose from the index. Can anyone tell me where I am going wrong?

I've encountered an issue with the View buttons I added to display more detailed information about the characters in the card bodies. When I click on the view button, it opens all the boxes instead of the one I selected. I've tried using a for lo ...

Retrieving the title value of the parent span element through a child node with the help of JavaScript or

Rebuilding the query. The HTML element structure is as follows: <li class="inner"><span class="plus" id="sidehome" title="siteHome">SiteHome</span> <ul style="display:none"> <li class="inner"> <span class="plus" id=" ...

Step-by-step guide on accessing values from a JavaScript object

I have a dictionary variable declared within a script tag on an HTML page. My goal is to retrieve the values associated with the "Roads" and "Intersections" keys, which change each time the page is refreshed. By capturing these values, I can then use JavaS ...

Separate modules in the Webpack.mix.js file don't produce any output files in the public folder

I've recently been tackling a Laravel project with an extensive webpack.mix.js file residing in the root directory, boasting nearly 5000 lines of code. In an effort to enhance organization and maintainability, I've opted to break it down into ind ...

I am having trouble getting Form.Select to work in my basic react-bootstrap application, despite following the guidelines provided in the react-bootstrap documentation. Can

I am new to utilizing "react-bootstrap with hooks" and currently in the process of creating a basic form. I have been following the guidance provided by react-bootstrap documentation, but I encountered an issue specifically with select/option form elements ...

Opt for using SVG elements over raster images in the canvas

My goal is to develop an application similar to this using JavaScript and canvas elements. To achieve this, I initially used KineticJS as the canvas library to create a draft. The teeth are represented by PNG images while the lines are drawn using Kinetic ...

Choose from the dropdown menu and verify with a CAPTCHA

I am currently working on my website. I need help with implementing a dropdown menu that allows for selecting multiple options at once. Can anyone provide guidance on JavaScript validation and also captcha implementation? The current script only allows for ...

An error occurred with nextJS and the current date. The text content does not align with the server-rendered HTML, raising a warning that the content does not

When working on a component with React, NextJS and M-UI, I encountered an issue while trying to retrieve a date. The error message I received was: Unhandled Runtime Error Error: Text content does not match server-rendered HTML. Warning: Text content did n ...

What is the best way to create an `isHook` function in my code?

Is there a way to determine if a function passed is a React Hook? isHook(useState); // returns true isHook(() => {}); // returns false; I am looking for a method to distinguish whether a function attached to an object property is a hook or not. In cas ...

How can I stop json_encode() from including the entire page in the JSON response when submitting a form to the same PHP script?

I only have a single index.php file in my project. I am aware that it's recommended to separate the logic from the view and use different files for PHP, JS, and HTML. This is just a test: <?php if($_SERVER["REQUEST_METHOD"] == "P ...

Is it possible to send form data to php using Ajax?

I need assistance with sending data from an HTML form to a PHP page. Here is the code for the form: <form onSubmit="return validateEmail()" style="text-align:center; clear:both"> <input type="text" id="ms_firstName" name="ms_firs ...