invoke a function from Controller within a JavaScript script

Using d3.js graphs, I successfully added the graph to the View cshtml page. Now, I want to dynamically fetch values for the graph from my database. To achieve this, I implemented the following function in the Controller:

    protected int CalculateReadinessAvg()
    {
        var avgReadiness = 0;
        var countItems = 0;
        foreach (var item in db.Reviews)
        {
            avgReadiness = avgReadiness + item.LecturerReadine;
            countItems++;
        }
        avgReadiness = avgReadiness / countItems;

        return avgReadiness;
    }

The above function works perfectly and returns the relevant value. Now, I need to incorporate this value into the JS code that renders the graph. Here is my attempt:

 var freqData = [
                 { State: '2013', freq: { LecturerReadine: '<%=CalculateReadinessAvg()%>', LecturerTransferRate: 412, LecturerAttitude: 674, LecturerKnowledge: 2001 } }
                , { State: '2014', freq: { LecturerReadine: 932, LecturerTransferRate: 2149, LecturerAttitude: 418, LecturerKnowledge: 4726 } }
                , { State: '2015', freq: { LecturerReadine: 832, LecturerTransferRate: 1152, LecturerAttitude: 1862, LecturerKnowledge: 2135 } }
                ];

However, the call to the function LecturerReadine: '<%=CalculateReadinessAvg()%>' doesn't seem to be working as expected. Any suggestions on how to resolve this?

Answer №1

In agreement with @Remy Grandin's statement, it is not possible to directly invoke the controller method from JavaScript. However, a C# function can be called within your .cshtml page by using @functions {..}

@functions{

 protected int CalculateAverage()
    {
        var avg = 0;
        var count = 0;
        foreach (var item in db.Reviews)
        {
            avg = avg + item.LecturerReadine;
            count++;
        }
        avg = avg / count;

        return avg;
    }

}

Subsequently, assign the calculated value.

var freqData = [
                 { State: '2013', freq: { LecturerReadine: '@CalculateAverage()', LecturerTransferRate: 412, LecturerAttitude: 674, LecturerKnowledge: 2001 } }
                , { State: '2014', freq: { LecturerReadine: 932, LecturerTransferRate: 2149, LecturerAttitude: 418, LecturerKnowledge: 4726 } }
                , { State: '2015', freq: { LecturerReadine: 832, LecturerTransferRate: 1152, LecturerAttitude: 1862, LecturerKnowledge: 2135 } }
                ];

Answer №2

When working with ASP MVC, it is not possible to call a C# function directly. However, one workaround is to convert the function into an action and then format a response in xml or json using the controller's Content() function.

Once you have the xml or json data prepared, you can utilize a simple javascript AJAX call to dynamically load this data into your graph.

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

Tips on scrolling down to find the text you're looking for

I attempted to scroll downwards in my application's window using the following JavaScript code: ((JavascriptExecutor) driver).executeScript("windows.scrollBy(0,500)"); Additionally, I tried to ensure a specific element is in view with this script: ...

Top recommendation for successfully submitting a JSF 2 form with potential ajax usage in case of encountering an error during submission

After clicking the submit button, the information is sent to a database using the button below. In the event that the button returns an error, I would like to implement AJAX to remove the form and its contents, replacing it with a text message. Edit: The ...

Ways to determine if a user is able to receive direct messages

I am facing an issue with a DM command. It seems to work properly, but when I try to DM a user who has disabled their DMs, user.send('test') triggers an error: UnhandledPromiseRejectionWarning: DiscordAPIError: Cannot send messages to this user ...

Enable data insertion on a Meteor server without requiring login authentication

I am looking to develop an API that enables other apps to add new data. However, I have encountered an issue while attempting to do so. The error message "User id is required" appears because there is no logged-in user present when inserting new data. Is i ...

The data that has been retrieved is not currently displayed within the Vue table

I'm currently exploring js/vue and I'm attempting to retrieve data from an API. There's a field where the value is used to fetch data from the API based on that keyword. When I check the console log, I can see that the data is being received ...

How can we properly access the DOM element generated by an {#each} loop in Svelte when it is clicked?

Using Svelte's {#each} functionality, I am reactively loading elements in the following way: {#each $items as item} <div> <Button on:click={someFunction}>{item.text}</Button> (*) </div> {/each} (*) a component t ...

Storing Material-UI Choices Using Redux State

Looking to integrate a Material-UI Select component with Redux data for persistent selections after page refresh. Within Redux, I have two arrays: the sourceTags array, consisting of clickable menu options, and the selectedTags array, containing the user& ...

Sending an object to a Vue 2 component and confirming its validity

I am working with a Vue component that has numerous props. <Field v-for="field in fields" :key="field.name" :name="field.name" :type="field.type" :label="field.label" :values="field.values" :value ...

What is the best way to transfer information between pages using onclick in node.js and express?

script1.js const database = new Datastore('database.db'); database.loadDatabase(); app.get('/api', (request, response) => { database.find({},(err,data)=> { if(err){ response.end(); return; ...

What is the best way to retrieve the js window object within emscripten's EM_JS function?

I'm looking to access the window.location in an EM_JS method in order to call a JavaScript method from C++. My attempted approach was: EM_JS(const char*, getlocation, (), { let location = window.location; let length = lengthBytesUTF8(location ...

Building a listview using Angular, MySQL, and Node.js

As a newcomer to Angular, I've been navigating my way through the learning process with some success but also encountering challenges. Although I've managed to resolve certain issues within the application, such as successfully inserting data int ...

Lazy loading images without the need to manually adjust the image structure

After experimenting with various LazyLoad options, I found that most of them required modifications to the src tag or the addition of a new tag. Is there a way to LazyLoad content without having to change the tag structure? I am extracting content fro ...

What is the best way to store dropdown values from a PHP foreach loop into local storage?

Within my shopping cart, I have added products that are stored in sessions. https://i.sstatic.net/qxz2V.png I am looking to save the selected options from all dropdowns even after the page is refreshed. When I refresh the page, my sessions need to be up ...

javascript: unable to modify currentTime in <audio> tag

Struggling to create a progress bar for my HTML5 audioplayer and implement a function to change the playing track's time by tapping. I opted to use input[range], but encountering an issue where the current play time does not update when tapping on the ...

Sending data retrieved asynchronously to child components' props

Currently, I am developing an application that fetches an array of news items from a remote source and showcases them on a webpage. After successfully calling the endpoint using $.getJSON(), as indicated by console logs, I integrated this call into the pa ...

Value-based JavaScript object prototype

Is there a way to ensure that every new object I create has its own unique dataTransfer property? For instance, when I try something like Object.prototype.dataTransfer = new DataTransfer();, I want a.dataTransfer.prop to remain 1 even if b.dataTransfer.pro ...

Issues with tracking changes in Vue.js when using reactive variables

After triggering a click event, I am attempting to choose a message from a json file. However, I am encountering an issue where the first click does not seem to select anything. Upon the second click, the selected messages are duplicated, and this pattern ...

The camera's rotation remains unchanged even after applying the transformation matrix

Is there a way to effectively apply a transformation matrix to a PerspectiveCamera? I have the transformation matrix and I am applying it to the Perspective camera using camera.applyMatrix(transformationMatrix); The camera.position is updated correctly, ...

Executing synchronous functions in NodeJS

I've been attempting to retrieve the number of records from a database using Node.js, but I'm running into an issue with synchronous requests. When I try to print the number inside the function, it works fine, but outside the function, it doesn&a ...

Guide on querying a single document in MongoDB that contains a specific value for an element within an array of arrays

I am facing an issue with a document that has an array of arrays and is using embedded documents in MongoDB. The collection name Orders looks like this: "_id" : "HjPGrdkffg7dQPtiX", "ListOrdersResult" : [ { "Orders" : { ...