What is the process for retrieving a function value from a JavaScript file and displaying it in an ASP.NET MVC view?

I am in the process of separating my view from JavaScript. In my view, I call a function in a JavaScript file to create a chart.

Below is the JavaScript file and the function:

 function createPieChart(chartID, pieChartData) {

chartID.kendoChart({
    dataSource: {
        data: pieChartData
    },
    series: [{
        type: "pie",
        field: "list",
        categoryField: "mm",
        padding: 0,
        labels: {
            visible: true,
        }
    }],
    seriesClick: onClick,
    tooltip: {
        visible: true,
        template: "${ category }"
    },
    legend: {
        position: "bottom"
    }
});

}

 function onClick(e) {    
 var clickedValue = e.category;

  }

Here is a snippet from my view:

  createPieChart($("#pieChart"), result);    

The issue I am facing is that the onClick() function in my JavaScript file is triggered when I click on the chart. I need to send this value back with an Ajax call in my view. How can I access this value in my view?

Answer ā„–1

Could you provide more details on where exactly you need this value in your view? What purpose does this value serve once it is received in the view?

If you have JavaScript available, it implies that you already have access to it in your view, as JavaScript logic runs within the view.

From your onDb(e) function, you can:

1) Retrieve the value and utilize it in the view using JavaScript logic.

In your separate JavaScript file, you might have a function like:

function onDb(e) {    
   var _clicked = e.category;
   return _clicked;
}

Within your view (.cshtml), you could include something similar to:

<script type="text/javascript">
    // Retrieve 'e' wherever needed 
    var requiredValue = onDb(e);
    // Implement any JavaScript / JQuery / Ajax logic ...
</script>

2) If the returned value is needed on the server side, you can make an AJAX request. Here's a guide on making such a request (MVC jquery ajax call with input parameter)

==== UPDATE AFTER COMMENT ====

You can access the onDb function in the same manner as shown in the second code snippet. However, retrieving the input parameter ā€œeā€ would involve some scripting.

Alternatively, a simpler approach in this scenario would be to move the "Ajax Call" inside the onDb(e) function. Update the onDb(e) function as follows ā€¦

function onDb(e) {    
var _clicked = e.category;

$.ajax({
    type: "POST",
    url: '@Url.Action("ControllerName", "ActionName")',
    contentType: "application/json; charset=utf-8",
    data: { valueToSend: _clicked },
    dataType: "json"
    });
}

On the server side, you would have an action similar to:

public class ControllerName : Controller
{
    [HttpPost]
    public ActionResult ActionName(string valueToSend)
    {
        // The required value is stored in the 'valueToSend' input parameter
        //... process as needed and return any ActionResult ...
        return Json("success", 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

Adjust the sizing of all fonts following the switch in font styles

Seeking help for adjusting font-size across a responsive web page design using different font families. font-family:Cambria, "Hoefler Text", "Liberation Serif", Times, "Times New Roman", serif; To achieve responsiveness, various media queries were applie ...

Tips for Ensuring the Longevity of my Node.js Server

After developing an application in Node js with express js, I am facing an issue where the server shuts down whenever I close the command prompt. To start the app, I use the following command: c:/myApp > npm start I attempted to resolve this problem b ...

Encountered an issue while executing the npm run dev command in a React project

Hello, I am a beginner with React.js and I am currently trying to set up a simple React application locally using webpack. However, when I run the npm run dev command, I encounter the following error: An error occurs in the command prompt after running np ...

express path variables are constantly loading

Despite seeing the dynamic id in the URL, I am facing an issue with the page continually loading. Below, you will find the route that HTML redirects us to and details about the database. // Route Parameter app.get('/detail/:id', (req, res) => ...

Using the information selected from the dropdown menu, the table was refined through an AJAX request

Having a small issue with ajax when working on my project. I have two actions in the view: <body> @Html.Action("SetSearchFilter") @Html.Action("FillTable") </body> The first action is a DropDownList: @Html.LabelFor(m => m.Manager, ...

JavaScript Alert: The Ajax XMLHttpRequest Response has Returned Null

Below is the code snippet: <script type="text/javascript"> var xmlhttp; $(document).ready(function (){ xmlhttp=new XMLHttpRequest(); ...

Export information from variables, lists, and dictionaries to a csv file

I am in the process of generating a csv file containing user information. So far, I have successfully created a csv file for variables like "name," "surname," and age. However, I also have data stored in lists and dictionaries with unknown lengths that I d ...

The Mootools element with the Object #<HTMLDivElement> does not support the addEvent method

$$('.img-default > a')[0] Retrieves the correct element from the DOM, but I am unable to attach an event. This bit of code: $$('.img-default > a')[0].addEvent('click', function(){ //GA code }); produces the followin ...

Unraveling the Distinctions: Identifying an Admin vs. a User within the API

When working with the express framework, I encounter a situation where I need to restrict access to certain API endpoints. For example, I have this line in the API: router.delete('/user',(req, res) => { //deleting...} Now, I want only an Adm ...

JS: Submitting form data through POST method but fetching it with GET method?

When using PHP to retrieve data, the $_POST method cannot be used; only $_GET. Why is that? Could it be that I am not sending my form data correctly? I assumed that by using request.open("POST"), the form would be processed as a POST request rather than a ...

ReactJS attempting to invoke a class function using a dynamically generated button

When attempting to access the deletePost(index) method from the ShowPost class using a dynamically rendered button within the render() step in React, I encounter an issue. The button labeled "click me" successfully retrieves and prints the first item in my ...

What circumstances allow @Inject to be optional in Angular?

My Angular service is simple yet causing errors. Here's the code snippet: // service.ts export class SimpleService { // ... } // component.ts @Component({ selector: 'my-component', templateUrl: 'components/mycomp/mycomp.ht ...

An excellent user interface that enables the user to easily reset a field to its original default value

Within my web-based application, users have the ability to customize values in specific textboxes. If they choose not to customize a value, the system will default to a predetermined option. I am looking to incorporate a feature that allows users to easil ...

Looking for assistance in resolving the error message: 'state' is not defined no-undef

I'm having some trouble adding a navbar to one of my projects as I keep encountering a failed to compile error. "Line 7:5: 'state' is not defined no-undef Line 9:5: 'handleClick' is not defined no-undef" import React, { ...

Looking to convert a jQuery function to plain JavaScript code?

Struggling with my homework, I must apologize for any mistakes in my English. My task involves creating a chat using node.js and I found some code snippets on a website "" which I used successfully. The issue now is that the chat relies on old jQuery libr ...

What is the process for showing a duplicate image in a dialog box once it has been selected on an HTML page?

I am experiencing an issue where the dialog box is displaying when I use the button tag, but not when I use the image tag. Can someone please assist? <img src='image.png' height='200px' widht='200px' id='1'> ...

Building a Slider component in a React class using Materialize CSS

I currently have a functioning slider implemented in a React function component. I am now looking to correctly integrate the slider below into a React class component. import * as React from 'react'; import Box from '@mui/material/Box'; ...

Text that appears as an HTML button is displayed after being compiled using the $

I am attempting to generate a pop up dialog with two buttons using JS code in angular. The script below is what I am using to create the buttons... var html = $('<button ng-click = "cancelAlert()" > Cancel</button > <button ng-click="c ...

Why is my Javascript for-loop returning "null" instead of the expected value?

Having trouble with the function below that is supposed to calculate the average of all elements in array1. Unfortunately, the function keeps returning null as the result. I can't seem to pinpoint the issue. var array1 = [46,73,-18,0,-442,779,5,1400] ...

If the socket cannot be found, an error callback will be activated

Below is the method I am using to send a message to a targeted socket connection. socket.broadcast.to(socketid).emit('message', JSON.stringify(data)); If the specified "socketid" does not exist, is there a mechanism in place to capture the erro ...