invoking a controller using a method in JavaScript

As I work on constructing a website using MVC 3 razor, there is a specific scenario that I am currently dealing with:

  1. One of the challenges involves a controller method:
public ActionResult MyControllerMethod(int parameter){
    ''perform some database operations
    IList<My_Custom> datafromDB = MyService.GetData(parameter);           

    'return data to my strong-typed view
    return View(datafromDB);
}
  1. Furthermore, in the situation outlined above, there is a strong-typed view where JavaScript plays a crucial role:
@model IList<My_Custom>
        
        <script type="text/javascript">
        
         function getData()
         { 
           var parameter = document.getElementById('myParamater').value;  
    
           $.get('/MyController/MyControllerMethod/' + parameter, function (data) {
                                   
              loadData();
    
           }
           );
       }
       
        function loadData() 
        { 
          clearData();
              
          datos = @Html.Raw(Json.Encode(Model));  
          
          //manipulate datos as needed
          
        }
    
        </script>

While the JavaScript call to the controller is functioning properly, I have encountered an issue regarding the strong-typed view not updating the @model's value accordingly. As a result, it continues to display the same information.

Despite debugging the action controller and confirming that it indeed returns varied data each time, I have yet to find a way to refresh the Model value within the strong-typed view.

I attempted to manipulate the data value from this line of code:

$.get('/MyController/MyControllerMethod/' + parameter, function (data) {

However, my attempts at doing so proved to be unsuccessful.

Answer №1

Your approach is causing issues because your action is returning a view instead of working as intended. Here's how your current code operates:

  • Data is loaded in the action, then a view is generated with json on the page
  • A request is sent to the server and HTML with JSON is received (all data stored in memory), then the JSON from the first step is accessed

This is how it should function:

  • Create the view
  • Send a request to the server using another method that returns JSON
  • Access the data
    public ActionResult YourJsonAction(int parameter)
    {
        IList dataFromDB = MyService.GetData(parameter);
        return Json(dataFromDB, JsonRequestBehavior.AllowGet);
    }

    function getData() 
    {  
       var parameter = $('#myParamater').val();   
       $.get('/MyController/YourJsonAction/' + parameter, function (data) { 
          //data fetched from YourJsonAction
       }); 
    }

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 for converting HTML content into a properly formatted text file

I have a user interface where users can perform various actions using ajax calls. Once the ajax call is completed, the results are displayed in a div with an id = "log". I want to provide users with an option (a button labeled Export) so that when they hav ...

Mongoose and BlueBird emerge victorious from fulfilling their promise

When using mongoose and bluebird as a promise framework, I encounter an error whenever I use "save" or "remove": Warning: a promise was created in a handler but was not returned from it I have spent days trying to resolve this issue. I have tried various ...

Creating an interactive dropdown menu in react.js

For a project I'm working on, the user can input data that is then sent to a MongoDB instance. There's also a search bar where users can retrieve the data and select a specific ID to view all corresponding document information in text fields. ht ...

Expanding and collapsing multiple tables in Material-UI

I'm currently working on creating a collapsible table using MaterialUI. At the moment, all my slides have collapses but they are connected to one state for "open", so when I open one slide, all the other slides also open. Here is an example sandbox t ...

Object with a specific name sitting within an array nested within another object

I have a node.js model that includes an array called keys containing multiple objects. I am looking to display these named objects in the view. Below is the model: var mongoose = require('mongoose'); var website = require('./website' ...

EINVAL: the argument provided is invalid for reading

I’m currently using node v11.5 and npm 6.4.1 on a flash drive labeled E, running on Windows 7. My goal is to install the latest version of the Netlify CLI. I followed the steps outlined at , and executed the following command: $ npm install netlify-cli ...

Retrieving data from handlebars variable in a client-side JavaScript file

When creating a handlebars view using hbs for the express js framework, I am faced with an issue of accessing the variables passed to the view from a separate JavaScript file. Here's an example: var foo = {{user.name}} This code obviously results ...

Having trouble uploading a file to Laravel using the jQuery .post method?

Here is a snippet of my HTML code: <input type="file" class="form-control" name="file-name" id="file-id"> This is the JavaScript function that is meant to send the file to an API: var file = $('input#file-id').val(); $.post('my/url/ ...

What is causing the slow performance of this JavaScript array retrieval?

I am working with a large array called frames_to_boxes, consisting of 5000 elements. Each element is an array of Objects belonging to the Box class: class Box { constructor(x, y, width, height, frame, object_class, id) { this.x = x; this.y = y; ...

Translating Bootstrap 5 into Angular components for version 13 and above

In Angular, the lack of support for optional host-elements and containerless components means that each component comes with its own div wrapper. However, when designing Bootstrap components, a host-less component (without an extra div) is needed to mainta ...

Configuring bitfinex-api-node with Node.js to efficiently handle data from the websocket connection

Apologies for the vague title of this question, as I am not well-versed in programming and even less so in node.js My goal is simple: I aim to utilize the bitfinex-api-node package (a node.js wrapper for the bitfinex cryptocurrency exchange) that I instal ...

Script in nodejs failing to execute in cron job

Hey there, I'm having trouble getting a nodejs script to work with a cronjob. I'm using a shell script to call the node script. I even created another nodejs script to test if the paths were correct, and that one is working fine. Here's the ...

Optimize data storage with javascript on Otree

I've been attempting to store the timestamp from a click in an Otree database, but I've tried using various codes without success. Here's the first code snippet: function myFunction() { var n = Date.now(); document.getElementById(" ...

Transforming intricate JavaScript objects into JSON format using Node.js

Currently, I am engaged in a web scraping project and my goal is to construct a JSON object from the gathered data. Below is an outline of the steps I am taking to achieve this: var submitButton = driver.findElement(By.className('btn btn-primary& ...

Steps to activating CORS in AngularJS

I've put together a demonstration using JavaScript to interact with the Flickr photo search API. Now, I'm in the process of transitioning it to AngularJs, and after some research online, I have come across the following configuration: Configurat ...

Struggling to properly interpret the unrefined data from Typeform's webhook

Utilizing the webhook feature of Typeform to convert results to JSON when a user submits the embedded survey is working perfectly when tested with RequestBin. However, after exposing my local app using ngrok with the command ngrok http 3000 and setting t ...

When using create-react-app, the value of 'process.env.NODE_ENV' can be accessed as either a string or a process object during runtime

Have you come across code that looks like this: if(process.env.NODE_ENV === 'development') { // Perform operations specific to DEVELOPMENT mode } Similarly, you might see process.env.NODE_ENV === 'production. When we run npm run ...

What is the reason skip does not function properly at the start of the aggregation pipeline, yet performs as expected at the conclusion of it?

Initially, the skip stage in this MongoDB database aggregation framework pipeline isn't functioning as expected: [ { $skip: (!offset)? 0 :(offset-1)*limit }, { $match: (query)? query : {} } , { $lookup: ..., ...

Mongoose: efficiently fetching the query response

How are you doing? I'm just starting to learn about mongoose and mongoDB, and I'm encountering some issues with a basic query. Here is the code snippet in question: function addVoterToElection(req, res) { let query = Election.findOne({ &apos ...

Save Chrome's console log programmatically

Can anyone provide insights on how to use javascript or nodejs to automatically extract the contents of Chrome's console for saving it into a file or database? ...